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
:
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<whoozit.Models.PictureModel>" %>
<td>
<%: Html.TextBoxFor(x => x.name) %>
<%: Html.ValidationMessageFor(x => x.name) %>
</td>
Notice that the partial is now strongly typed to whoozit.Models.PictureModel
instead of IList<whoozit.Models.PictureModel>
. Now all that is left is to include this partial from the main view:
<%: Html.EditorFor(x => x.Pictures) %>
Where Pictures
is a property of type IList<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.ascx
as the type name of the list elements and located in ~/Views/Home/EditorTemplates
or ~/Views/Shared/EditorTemplates
folder.
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 name
property to Name
. It's just feels more natural to write and read:
<%: Html.TextBoxFor(x => x.Name) %>