Dynamically add new fields with an editor template

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

+4
source share
2 answers

It's not too late to answer here,

I am looking for something useful to me link. Now I know how you can add the dynamic addition of a download file by adding / removing an element to the IEnumerable model property in EditorFor .

For your solution, I think UIHint and the template can do whatever you want. Inside the template, you can foreach and specify the formatting for id .

0
source

Checkout the Jarrett Meyer Blog, Nested Collection Models in MVC3 .
Summarized in this answer to SO.

0
source

All Articles