Extension to: How do you handle multiple submit buttons in ASP.NET MVC Framework?
Let us say a view is composed of partial views bound with related models, let’s say a student is required to provide multiple contact persons(partial view bound to Person model) and multiple contact numbers(partial view bound to a model) to get registered, sorry for the bad example. Once a contact person or number is added, an action (child postback or whatever) is called which validates the related model (not student model), adds it in a list and returns to the same page for further processing. Once all are added, the parent/master action validates whole student model and processes it.
How to validate the specific model for which an action is being called, add it to the page and return the same student view with added values in response?
This solution uses #2 (Session) since its simpler to code however this demonstrates the principles.
Views
Index View:
@using StackOverflow.Models <div> @{ Html.RenderPartial("PersonGrid", Model.Persons, new ViewDataDictionary()); } @Html.Partial("NewPerson", new Person()) @{ Html.RenderPartial("ContactGrid", Model.Contacts, new ViewDataDictionary()); } @Html.Partial("NewContact", new Contact()) @using(Html.BeginForm("Validate", "Home", FormMethod.Post)) { <input type="submit" value="Validate" /> } </div>Person Grid
@model IList <table> <thead> <tr> <td>First Name</td> <td>Last Name</td> </tr> </thead> <tbody> @if (Model != null && Model.Any()) { foreach (var person in Model) { <tr> <td>@person.FirstName</td> <td>@person.LastName</td> </tr> } } else { <tr> <td colspan="2" style="text-align: center">No persons available</td> </tr> } </tbody> </table>Contact Grid
@model IList <table> <thead> <tr> <td>Phone</td> </tr> </thead> <tbody> @if (Model != null && Model.Any()) { foreach (var contact in Model) { <tr> <td>@contact.Phone</td> </tr> } } else { <tr> <td>No contacts available</td> </tr> } </tbody> </table>New Person
@model StackOverflow.Models.Person @using (Html.BeginForm("NewPerson", "Home", FormMethod.Post)) { <div> @Html.Hidden("PersonViewState", TempData["PersonViewState"]) @Html.LabelFor(m => m.FirstName)<br /> @Html.TextBoxFor(m => m.FirstName)<br /> <br /> @Html.LabelFor(m => m.LastName)<br /> @Html.TextBoxFor(m => m.LastName)<br /> <br /> <input type="submit" value="Submit" /> </div> }New Contact
@model StackOverflow.Models.Contact @using (Html.BeginForm("NewContact", "Home", FormMethod.Post)) { <div> @Html.LabelFor(m => m.Phone)<br /> @Html.TextBoxFor(m => m.Phone)<br /> <br /> <input type="submit" value="Submit" /> </div> }Models
Helpers
Controller