<ul>
@{int i=0;}
@foreach (var entry in Model.PhoneNumberEntries)
{
<li>
<span>@entry.PhoneNumber<span>
@Html.TextBoxFor(m=>Model.PhoneNumberEntries[i].PhoneNumber)</li>
i++;
}
</ul>
This seems a little too verbose for me… is there way to get around creating the counter with having to resort to the standard for loop?
Yeah it seems too verbose to me as well. Even the loop seems too verbose as you don’t need it if you use editor templates.
and then obviously you would define a custom editor template that will automatically be rendered for each element of the
PhoneNumberEntriescollection (~/Views/Shared/EditorTemplates/PhoneNumberEntry.cshtml):You don’t even need to write loops as templates work by convention.
Notice that the name and the location of the editor template is important. It should be located either inside
~/Views/Shared/EditorTemplatesif you want to share this template between views belonging to different controllers in your application and it is the location where ASP.NET MVC will first look for it. Or you could also put it inside~/Views/XXX/EditorTemplateswhereXXXis the name of the current controller. Then name of the editor template must be the name of the type used as agrument for the collection property.So if you had no your main view model:
the name of the corresponding template would be
FooBarViewModel.cshtmland obviously it will be strongly typed toFooBarViewModel.