Click here to Skip to main content
15,850,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm afraid I can't understand the following


I'm in a view and this is my model type declaration

@model IEnumerable<BeerCupMVC.Models.SomeObject>

Please consider the line

@Html.DisplayNameFor(model => model.SomeObjectName)

It displays the DisplayName annotation of the property SomeObjectName but why do we put "model" and why does it works if we do the following?

@Html.DisplayNameFor(xyz => xyz.SomeObjectName)

@foreach (var item in Model) {
            @Html.DisplayFor(modelItem => item)
            @Html.ActionLink("Edit", "Edit", new { id=item.SomeObjectID }) |
            @Html.ActionLink("Details", "Details", new { id=item.SomeObjectID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.SomeObjectID })

It's ok for me to understand the loop stuff but how to explain the "modelItem" in this syntax?

That's a lambda expression. When an expression works on a type it is written in the format of

(x => ...)

"x" is arbitrary, it can be anything you want, it is effectively a temporary variable of the type that the expression works on. So for;

List<string> myData = new List<string>();
myData.Where (abc => abc != "Hello);

What we're saying in the "Where" left of the "=>" is that abc is a variable of type string, and right of the => is the expression we want to evaluation, so where the data in abc is not Hello. The Where will then loop through each instance in the list, load that instance into the variable abc, and then check if abc != "Hello".

So there is no significance to what you call the variable, it could be "model", "m" or even

@Html.DisplayNameFor(supercalifragilisticexpialidocious => supercalifragilisticexpialidocious.SomeObjectName)

People tend to chose model or m as it makes it obvious what the function is acting on. Just don't confuse that "model" with the "@model" directive at the top of the view, or the "Model" property :)
Share this answer
Amit Jadli 22-Jan-16 7:02am    
You need to learn lambda expression.

1. model => model.SomeObjectName

In the above code, model refers to the
@model IEnumerable<BeerCupMVC.Models.SomeObject>
which is SomeObject in your case. So this is significant in your case.

2. @Html.DisplayFor(modelItem => item)

The modelItem in the above lambda is insignificant which means you are passing a parameter but not using it and you are working on the var item rather.
In general, the input parameter name is irrelevant , you could use any name but it has to come from a collection or an object.

Hope this helps.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900