Asp.net mvc 4 ASP.NET MVC 4:型号为';内部列表
我有一个ViewModel,它扩展了一个众所周知的基类,以允许共享视图读取公共属性。这是故意的 我还有一些页面显示模型中包含的实体列表的详细信息。以下代码提供了一个示例:Asp.net mvc 4 ASP.NET MVC 4:型号为';内部列表,asp.net-mvc-4,Asp.net Mvc 4,我有一个ViewModel,它扩展了一个众所周知的基类,以允许共享视图读取公共属性。这是故意的 我还有一些页面显示模型中包含的实体列表的详细信息。以下代码提供了一个示例: public abstract class AbstractViewModel { public Exception lastError; //If not null triggers a big warning } public class Cat{ [Display(...)] pub
public abstract class AbstractViewModel {
public Exception lastError; //If not null triggers a big warning
}
public class Cat{
[Display(...)]
public string Name;
}
public class CatListViewModel: AbstractViewModel {
public IEnumerable<Cat> cats;
}
公共抽象类AbstractViewModel{
公共异常lastError;//如果不为null,将触发一个大警告
}
公猫{
[显示(…)]
公共字符串名称;
}
公共类CatListViewModel:AbstractViewModel{
公猫;
}
现在,我的局部视图需要使用常见的MVC方式显示猫的列表
@model Org.Zighinetto.CatListViewModel
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Cats.Name) //Doesn't work!!
</th>
</tr>
@foreach (var item in Model.Cats)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
@model Org.Zighinetto.CatListViewModel
@Html.DisplayNameFor(model=>model.Cats.Name)//不起作用!!
@foreach(Model.Cats中的var项)
{
@DisplayFor(modelItem=>item.Name)
}
不幸的是,我不能将集合作为参数使用DisplayNameFor
问题是
鉴于上述数据模型,并且鉴于设计原因,我不想将模型性质更改为IEnumerable
当表达式涉及集合时,尤其是当该集合为空时,如何将显示名称(它是
Cat
类的属性)绑定到DisplayNameFor
方法或任何等效方法?否则,我将如何修复上述编译错误?在这种情况下,DisplayNameFor
的正确语法是什么?我很幸运地找到了
基本上
Html.DisplayNameFor(Model=>Model.Cats.FirstOrDefault().Name)
是有效的,因为即使没有Cat,运行时也会正确地反映类型Cat
,在代码中有一些事情需要注意,以防止出现空异常
首先,您需要初始化您的Cats
集合,以便当您的代码出于有效原因而不这样做时,并且实际上发生了这种情况,可以保护您免受空异常的影响。因此,您可以这样编写模型:
public class CatListViewModel: AbstractViewModel {
public CatListViewModel() {
Cats = new List<Cat>();
}
public IEnumerable<Cat> Cats;
}
@戴维坦西,因为杰切隆不能,现在不行。
<th>
@if (Model.Cats.Any()) {
@Html.DisplayNameFor(model => model.Cats.First().Name)
}
</th>