I have a partial view that renders a list of objects into a table format and allows editing of the values…
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<whoozit.Models.PictureModel>>" %>
<% foreach (whoozit.Models.PictureModel p in Model)
{ %>
<td>
<%: Html.TextBox("name",p.name) %>
<%: Html.ValidationMessage(p.name) %>
</td>
<% } %>
I’m wanting to refactor this to take advantage of the strongly typed html helpers in mvc2. I am running into difficulty understanding how to create the lambda expressions and was hoping for some help. the following doesn’t seem quite correct to me.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<whoozit.Models.PictureModel>>" %>
<% foreach (whoozit.Models.PictureModel p in Model)
{ %>
<td>
<%: Html.TextBoxFor(???) %>
</td>
<% } %>
First of all you shouldn’t be iterating in a view. Iterating means loops, loops mean C#/VB.NET, C#/VB.NET in a view leads to spaghetti code.
I would recommend you using Editor Templates. This way you don’t need to write loops in your views. Add the following file in
~/Views/Home/EditorTemplates/PictureModel.ascx:Notice that the partial is now strongly typed to
whoozit.Models.PictureModelinstead ofIList<whoozit.Models.PictureModel>. Now all that is left is to include this partial from the main view:Where
Picturesis a property of typeIList<whoozit.Models.PictureModel>on your main view model. This will automatically invoke the partial for each element of the collection so that you don’t need to write ugly loops in your views.It just works by convention: the partial needs to be called
PictureModel.ascxas the type name of the list elements and located in~/Views/Home/EditorTemplatesor~/Views/Shared/EditorTemplatesfolder.Editor/Display templates will make your views much more elegant.
Remark: In .NET the convention is property names to start with capital letter, so I would recommend you renaming the
nameproperty toName. It’s just feels more natural to write and read: