为什么生成的DataBaseManagerController表头是使用ASP MVC 4中的lambda表达式生成的
我为我的解决方案生成了StoreManagerController
。 Visual Studio 2013生成了此类StoreManager/Index.cshtml view
@model IEnumerable @{ ViewBag.Title = "Index"; } Index
@Html.ActionLink("Create New", "Create")
@Html.DisplayNameFor(model => model.Genre.Name) @Html.DisplayNameFor(model => model.Artist.Name) @* @Html.DisplayNameFor(model => model.Title)*@ TITLE @Html.DisplayNameFor(model => model.Price) @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Genre.Name) @Html.DisplayFor(modelItem => item.Artist.Name) @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.Price) @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) | @Html.ActionLink("Details", "Details", new { id=item.AlbumId }) | @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId }) }
问题:
1.为什么表头由以下生成: @Html.DisplayNameFor(model => model.Title)
不仅仅是Title
或者至少是@Html.DisplayNameFor(model.Title)
。
2.Ind DisplayNameFor
方法返回字段的名称,因此对于model => model.x,它返回x? 这有点像Java中的reflection吗?
这里需要lambda表达吗?
结果:
您的所有问题基本上都是同一个问题的变体。 DisplayNameFor
用于返回属性的面向用户的名称。 在最基本的场景中,它只是返回属性名称本身,如果没有在表达式中实际指定属性名称,这将无法工作,所以有理由问,“为什么不只是硬编码名称”。 当您通过添加以下内容为以下内容指定属性的显示名称时,真正的好处就来了:
[Display(Name = "My Awesome Title")] public string Title { get; set; }
现在,它返回“My Awesome Title”而不是“Title”,如果您以后决定将该显示名称更改为“My Super Awesome Title”,则只需更改一次,并且在任何地方使用DisplayNameFor
,该值会自动更新。
该表达式对于较低级别的原因是必要的。 如果你刚刚传递了model.Title
,那么传递的将是属性的值。 表达式用于传递属性本身 ,然后DisplayNameFor
使用reflection来获取适当的显示名称。