views:

204

answers:

1

I have a model:

public class MyListModel
{
    public int ID {get;set;}
    public List<User> Users{get;set;}
}

How do I use the Html.EditorFor method inside a foreach?

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyListModel>" %>
<table>
    <tr>
        <th></th>
    </tr>
<% foreach (var item in Model.Users) { %>
    <tr>
        <td>
            <%= Html.EditorFor(item.Enabled)%>
        </td>
    </tr>
</table>
+5  A: 
<%= Html.EditorFor(x=> item.Enabled)%>
Alexander Taran
I'm fairly sure that doesn't work. Have you tested that?
Nathan Taylor
Definitely works. The "right hand side" of a lambda does not have to reference the "left hand side".
Eilon
Well gee, would you look at that! That will clean up some of the Html.RenderPartial()s I've been using unnecessarily.
Nathan Taylor
You're right, it does work. I didn't think it would either. Thanks.
Jeremy
Keep in mind that lambdas are just method definition. A method can take a parameter "x" and not actually use it in the method body. A neat trick, for sure! I highly recommend reading Brad Wilson's 5-part series on templated helpers: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
Eilon
I never realized that about lambdas; where have I been all this time?!
Nathan Taylor