Why in generated DataBaseManagerController table h

2019-06-08 23:43发布

I have generated StoreManagerController for my solution. Visual Studio 2013 generated such StoreManager/Index.cshtml view

@model IEnumerable<MvcMusicStore.Models.Album>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Genre.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Artist.Name)
        </th>
        <th>
           @* @Html.DisplayNameFor(model => model.Title)*@
            TITLE
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th></th>
    </tr>

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

</table>

Questions:

1.Why table header is generated by : @Html.DisplayNameFor(model => model.Title) not just Title or at least @Html.DisplayNameFor(model.Title).

2.Is DisplayNameFor method returns name of the field, so for model => model.x it returns x? Is this something like reflection in Java?

3.Is lambda expression necessary here?

Result: enter image description here

1条回答
Emotional °昔
2楼-- · 2019-06-09 00:45

All your questions are basically a variation on the same one. DisplayNameFor is used to return the user-facing name for a property. In the most basic of scenarios it's just going to return the property name itself, which wouldn't work without actually specifying the property name in the expression, so it's reasonable to ask, "why not just hard-code the name". The real benefit comes when you specify a display name for the property by adding something like:

[Display(Name = "My Awesome Title")]
public string Title { get; set; }

Now, it returns "My Awesome Title", instead of "Title", and if you later decide to change that display name to "My Super Awesome Title", you change it in just once place, and everywhere you've used DisplayNameFor, the value is automatically updated.

The expression is necessary for a lower-level reason. If you just passed model.Title, what would be passed would be the value of the property. The expression serves to pass the property, itself, which DisplayNameFor then uses reflection on to get the appropriate display name.

查看更多
登录 后发表回答