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
In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view.
Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
To pass the strongly-typed data from Controller to View using ViewData, we have to make a model class then populate its properties with some data and then pass that data to ViewData dictionary as Value and selecting Key's name is the programmer's choice.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With