In my MVC4 project, I have a category view model with a collection of product view models. I use the editor template to render one product presentation model and pass it a collection of product presentation models:
Category view model:
@model CategoryViewModel @using MVC4PartialViews.Models.ViewModels <div class="editor-field"> @Html.EditorFor(model => model.CategoryName) @Html.ValidationMessageFor(model => model.CategoryName) </div> @Html.EditorFor(x => x.Products)
An editor template that displays each Product in the collection:
<div class="editor-field"> @Html.EditorFor(model => model.ProductName) @Html.ValidationMessageFor(model => model.ProductName) </div> // etc.
This works very well because it automatically detects and indexes the items correctly, so all products are sent back as part of the parent category view model - this is what it outputs:
<div class="editor-field"> <input class="text-box single-line" id="Products_0__ProductName" name="Products[0].ProductName" type="text" value="Add 1st product for this Category" /> <span class="field-validation-valid" data-valmsg-for="Products[0].ProductName" data-valmsg-replace="true"></span> </div>
I need users to be able to add and remove products. To add a new one, I somehow need to dynamically visualize the editor template to create a new Product and have each field indexed / named correctly, i.e. if I already have 2 Products (with index 0 and 1), then the new Product will need to be named as such as:
Products[2].ProductName
I read this article by Steve Sanderson, but it seems awkward and it indexes its fields using Guid, not a sequential index field:
Editing a Variable List in MVC2
TIA
source share