【问题标题】:Check system.nullreferenceexception检查 system.nullreferenceexception
【发布时间】:2015-03-15 09:32:38
【问题描述】:
我的代码如下:
@{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>@UName</text>
如果 ViewBag.UnionList 为空,则它通过 system.nullreferenceexception。如何检查和验证这个?
【问题讨论】:
标签:
c#
asp.net-mvc
exception
【解决方案1】:
好吧,您正在调用FirstOrDefault - 如果序列为空,则返回 null(或者更确切地说,元素类型的默认值)。所以你可以用单独的语句来检测:
@{var sequence = (IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList;
var first = sequence.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
var name = first == null ? "Some default name" : first.Name; }
<text>@UName</text>
在 C# 6 中,使用 null 条件运算符更容易,例如
var name = first?.Name ?? "Some default name";
(这里略有不同 - 如果Name 返回 null,则在后面的代码中您最终会使用默认名称;在前面的代码中您不会。)
【解决方案2】:
首先,你不应该在视图中做这种工作。它属于控制器。所以cshtml应该是:
<text>@ViewBag.UName</text>
在控制器中,使用类似的东西:
var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;