Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LabelFor() in a foreach

Tags:

I have a view with a strongly-typed model associated with it

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"                   Inherits="System.Web.Mvc.ViewPage<SomeNamespace.SomeViewModel>" %> 

The SomeViewModel looks like this

class SomeViewModel {     public IEnumerable<Foo> Foos {get; set;} } 

and say Foo is

class Foo {    public string Bar {get; set;} } 

and in the view

<% foreach (var item in Model.Foos) { %>     <tr>         <td>             <%= Html.LabelFor(f => f.Bar) %>         </td> 

I'm not sure how to display Bar property in item using Html.LabelFor()

Can someone help me with this?

Thanks,

like image 772
Professor Chaos Avatar asked Sep 16 '11 13:09

Professor Chaos


1 Answers

Do this instead:

<% foreach (var item in Model.Foos) { %>       <tr>               <td>                       <%= Html.LabelFor(f => item.Bar) %>               </td> <% } %> 

Instead of f => f.Bar do f => item.Bar, where item is the name of the variable in your foreach loop.

Here is the much more beautiful razor syntax :)

@foreach( var item in Model.Foos ) { <tr>     <td>         @Html.LabelFor(f => item.Bar)     </td>     <td>         @Html.DisplayFor(f => item.Bar)     </td> </tr> } 
like image 171
Dismissile Avatar answered Nov 06 '22 03:11

Dismissile