简体   繁体   English

检查system.nullreferenceException

[英]Check system.nullreferenceexception

My code as follows: 我的代码如下:

@{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>@UName</text>

if ViewBag.UnionList is empty then it troughs system.nullreferenceexception.How to check and validate this? 如果ViewBag.UnionList为空,则它通过system.nullreferenceexception。如何检查和验证?

Well, you're calling FirstOrDefault - that returns null (or rather, the default value for the element type) if the sequence is empty. 好吧,您正在调用FirstOrDefault如果序列为空,则返回null(或元素类型的默认值)。 So you can detect that with a separate statement: 因此,您可以使用单独的语句检测到该错误:

@{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>

In C# 6 it's easier using the null conditional operator, eg 在C#6中,使用空条件运算符会更容易,例如

var name = first?.Name ?? "Some default name";

(There's a slight difference here - if Name returns null, in the latter code you'd end up with the default name; in the former code you wouldn't.) (这里有一个细微的区别-如果Name返回null,则在后面的代码中,您将使用默认名称;在前一个代码中,您将不会使用。)

First of all, you should not be doing this kind of work in the View. 首先,您不应该在View中进行此类工作。 It belongs in the Controller. 它属于控制器。 So the cshtml should simply be: 因此,cshtml应该只是:

<text>@ViewBag.UName</text>

And in the controller, use something like: 在控制器中,使用类似:

var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM