【发布时间】:2011-03-05 01:59:38
【问题描述】:
我正在努力寻找一种方法来处理我的视图模型中的空值。其中一些值是我模型中的嵌套或导航对象。如何在不将逻辑引入视图的情况下防止视图抛出空引用错误?这似乎很容易,但这是一天的结束。
我有一个带有一些导航属性的视图模型,如下所示:
ViewModel.cs
public class ViewModel
{
public ViewModel () {}
public ViewModel (Contact contact, IDemographicService demographicService)
: this()
{
Id = contact.Id;
Name = contact.Name;
EthnicityId = contact.EthnicityId;
if(EthnicityId > 0 || EthnicityId != null)
Ethnicity = deomographicService.GetEthnicityById((int)contact.EthnicityId);
}
public int Id {get;set;}
public string Name {get;set;}
public int? EthnicityId {get;set;}
public Ethnicity Ethnicity {get;set;}
}
我将跳过控制器,因为这不是我问题的重点。 (我知道逻辑可以放在控制器中,但我选择将它放在 ViewModel 中)。
MyView.cshtml
@model ViewModel
<ul>
<li>@Model.Name</li>
<li>@Model.Ethnicity.Name</>//This is the null reference.
</ul>
我想我可以只定义一个“EthnicityName”字符串(如果 null 返回 null)而不是整个对象,但是在某些情况下我需要 Ethnicity 对象的多个属性。这消除了种族,无论是在视图模型、控制器还是视图中。简而言之,我该如何处理 null.null?难住了。谢谢。
【问题讨论】:
标签: .net asp.net-mvc-3 view viewmodel