MVC 3: HTML.DisplayFor and Lambda Expression

I found other topics about this, but none of them made me understand what I was trying to understand.

I am learning MVC 3 and I have problems wrapping my head around lambda expressions that come with @ HTML.DisplayFor () in a forest pattern.

I am working with a sample application MvcMusicStore, a view created using forests is as follows:

@model IEnumerable<MvcMusicStore.Models.Album>

...

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Genre.Name)
        </td>

I understand that DisplayFor is an HTML extension method and that it takes an expression as a parameter. I explored lambda expressions and understood them in other contexts, such as enumerated strings. For instance:

cities.Where(s => s.StartsWith("L"));

, (-) (s.startswith..), , , . MVC 3. modelItem . "modelItem" :

@Html.DisplayFor(iAmWearingShortPantsToday => item.Genre.Name)

, . , "modelItem" . , ?

Lambda (, , ), :

@(Html.DisplayFor(delegate(IEnumerable<MvcMusicStore.Models.Album> modelItem) { return item.Genre.Name; }))

, , . :

CS1946:

:

"modelItem" ? HTML.DisplayFor() modelItem? , ?

, , .

+5
2

. modelItem . item, . item - , foreach.

, modelItem => item.Genre.Name ASP.NET MVC, . . . . . , .

, :

@model IList<MvcMusicStore.Models.Album>
...

@for (var i = 0; i < Model.Count; i++) {
    <tr>
        <td>
            @Html.DisplayFor(x => x[i].Genre.Name)
        </td>
        ...
    </tr>
}

. ? /:

@model IEnumerable<MvcMusicStore.Models.Album>
...
@Html.DisplayForModel()

, ASP.NET MVC (~/Views/Shared/DisplayTemplates/Album.cshtml)

@model Album
<tr>
    <td>
        @Html.DisplayFor(x => x.Genre.Name)
    </td>
    ...
</tr>
+2

, , , DisplayFor, . ( ) .

TextBoxFor, , .

, html-helper , , ( , -, ).

0

All Articles