LeftOnTheMoon
LeftOnTheMoon

Reputation: 973

Don't understand this variable in ASP.NET MVC 5 scaffolding

So in ASP.NET MVC 5, I scaffolded a pretty simply model just to look at the code it produced. In one of the HTML Helpers, however, there is an object that I can't seem to find the origin of. It is in this line:

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

I am referring to the modelItem. Where is this coming from? Here is the rest of the simple view file:

@model IEnumerable<MVCtester.Models.Dog>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Breed)
            </th>
            <th></th>
        </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Breed)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ID })
            </td>
        </tr>
    }

    </table>
</body>
</html>

Here is the controller:

// GET: Dogs
public ActionResult Index()
{
    return View(db.Dogs.ToList());
}

So it appears there is no visible origin of modelItem. Where does this come from and what is its purpose? Thank you!

Upvotes: 0

Views: 82

Answers (1)

DavidG
DavidG

Reputation: 118937

Html.DisplayNameFor() takes an expression as a parameter, the full signature is:

public static MvcHtmlString DisplayFor<TModel, TValue>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, TValue>> expression);

The lamda expression inside that you mention modelItem => item.Name is inside a foreach loop so you can't use the "normal" expression of model => model.Property, instead the input parameter in this case modelItem is not needed as you are only using the iterator variable item. So it can be absolutely called anything you like.

Upvotes: 1

Related Questions