【发布时间】:2014-12-25 09:35:34
【问题描述】:
假设我们有这样的模型:
public class MyItem
{
[DisplayName("TheTitle")]
public string Title {get; set;}
}
如果是编辑/详细信息/删除视图中的简单模型,我们可以像这样使用@Html.DisplayNameFor:
@model MyItem;
@Html.DisplayNameFor(model => model.Title) //Result "TheTitle"
@Html.EditorFor(model => model.Title)
或在列表视图中:
@model IEnumerable<MyItem>;
foreach (var myItem in Model)
{
@Html.DisplayNameFor(model => model.Title) //Result "TheTitle". Seems the model is still MyItem, rather than Inemerable<MyItem>.
@Html.EditorFor(model => model.Title)
}
这使得在许多视图上更改属性的标题变得更加容易。
但是复杂的视图模型例如:
public MyViewModel
{
[DipslayName("Count")]
int Count;
IEnumerable<MyItem> MyItems;
}
在这种情况下,如何显示“TheTitle”?
@model IEnumerable<MyViewModel>;
@Html.DisplayNameFor(model => model.Count) //Result "TheCount".
@Html.EditorFor(model => model.Count)
@foreach (var myItem in Model.MyItems)
{
@Html.DisplayNameFor(model => ???) //How to display "TheTitle" here?
@Html.EditorFor(model => ???) //Same question, I think.
}
我在这里尝试了一些硬代码(字符串“@: TheTitle”而不是 DisplayNameFor),但认为这不是一个好习惯。
谢谢,圣诞快乐。
【问题讨论】:
-
您尚未使用
DisplayAattribute标记您的MyItems -
您能举个例子吗?谢谢。