Asp mvc partially with model and ViewDataDictionary - how do I access ViewDataDictionary?

I am creating a form that updates two related models, for this example a project with a collection of tasks, I want the controller to accept one project that has a collection of tasks loaded from the form input. I have this job essentially below code without partial.

This may seem silly, but I can't figure out how to access the counter (i) from partial?

Model

public class Project { public string Name { get; set; } public List<Task> Tasks { get; set; } } public class Task { public string Name { get; set; } public DateTime DueDate { get; set; } } 

Create.cshtml (view)

 @model MyWebApp.Models.Project @using(Html.BeginForm("Create", "Project", FormMethod.Post, new { id = "project-form" })) { <div> @Html.TextBox("Name", Model.Name) </div> @for(int i = 0; i < Model.Tasks.Count; i++) { @Html.Partial("_TaskForm", Model.Tasks[i], new ViewDataDictionary<int>(i)) } } 

_TaskForm.cshtml (partial view)

 @model MyWebApp.Models.Task <div> @Html.TextBox(String.Format("Tasks[{0}].Name", 0), Model.Name) </div <div> @Html.TextBox(String.Format("Tasks[{0}].DueDate", 0), Model.DueDate) </div 

NOTE: String.Format above I am hardcoding 0, I want to use the ViewDataDictionary parameter bound to the variable i from the calling View

+49
asp.net-mvc
Feb 01 '11 at 16:28
source share
1 answer

I think I published too soon. In this thread was the answer I was looking for

asp.net MVC RC1 RenderPartial ViewDataDictionary

I ended up using this short syntax

 @Html.Partial("_TaskForm", Model.Tasks[i], new ViewDataDictionary { {"counter", i} } ) 

Then in partial view

 @model MyWebApp.Models.Task @{ int index = Convert.ToInt32(ViewData["counter"]); } <div> @Html.TextBox(String.Format("Tasks[{0}].Name", index), Model.Name) </div> <div> @Html.TextBox(String.Format("Tasks[{0}].DueDate", index), Model.DueDate) </div> 
+97
Feb 01 '11 at 16:57
source share



All Articles