Reputation: 20614
I am creating a form which updates two related models, for this example a Project with a collection of Tasks, I want the controller to accept a single Project which has its Task collection loaded from the form input. I have this working, essentially the below code without a partial.
This might sound silly but I cannot figure out how to access the counter (i) from the 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 the String.Format above I am hardcoding 0, I want to use the ViewDataDictionary parameter which is bound to the variable i from the calling View
Upvotes: 71
Views: 87973
Reputation: 20614
Guess I posted too soon. This thread had the answer I was looking for
asp.net MVC RC1 RenderPartial ViewDataDictionary
I ended up using this terse 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>
Upvotes: 142