我的代码如下:
@{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>@UName</text>
如果ViewBag.UnionList为空,那么它会通过system.nullreferenceexception.How来检查并验证这个?
答案 0 :(得分:2)
好吧,你正在调用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中,使用空条件运算符更容易,例如
var name = first?.Name ?? "Some default name";
(这里有一点点差别 - 如果Name
返回null,在后面的代码中你最终会得到默认名称;在前面的代码中你不会。)
答案 1 :(得分:1)
首先,你不应该在View中做这种工作。它属于Controller。所以cshtml应该只是:
<text>@ViewBag.UName</text>
在控制器中,使用类似:
的内容var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;