Suppose I have a simple model to explain the purpose:
public class Category
{
...
public IEnumerable<Product> Products { get; set; }
}
View:
@model Category
...
<ul>
@Html.EditorFor(m => m.Products)
</ul>
EditorTemplate:
@model Product
...
<li>
@Html.EditorFor(m => m.Name)
</li>
Note that I don't have to define the EditorTemplate for IEnumerable<Product>
, I can only create it for the Product
model and MVC framework is smart enough to use its own template for IEnumerable. It iterates through my collection and calls my EditorTemplate.
The output html will be something like this
...
<li>
<input id="Products_i_Name" name="Products[i].Name" type="text" value="SomeName">
</li>
which I can post to my controller after all.
But why doesn't the MVC do the trick when I define EditorTemplate with a template name?
@Html.EditorFor(m => m.Products, "ProductTemplate")
In that case I have to change the type of the property to IList<Product>
, iterate through the collection by myself and call the EditorTemplate
@for (int i = 0; i < Model.Products.Count; i++)
{
@Html.EditorFor(m => m.Products[i], "ProductTemplate")
}
which seems kind of dirty workaround to me. Is it any other, cleaner solution to do this?
There, now I only owe Darin 9999 beers.
The simple answer is no, it sucks badly, I completely agree with you, but that's how the designers of the framework decided to implement this feature.
So what I do is I stick to the conventions. Since I have specific view models for each views and partials it's not a big deal to have a corresponding editor template, named the same way as the type of the collection.