当我的模型为null时,如何避免View的foreach循环中出现NullReferenceException? [英] How does one avoid a NullReferenceException in a foreach loop within a View when my model is null?

查看:84
本文介绍了当我的模型为null时,如何避免View的foreach循环中出现NullReferenceException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过控制器传递null值时,在我的View中出现以下代码,出现"NullReferenceException未由用户代码处理"错误.在某些情况下,我想传递一个空值,但是在发生这种情况时,我不希望引发错误.我应该将代码更改为什么?

I get a "NullReferenceException was unhandled by user code" error with the following code in my View when I pass in a null value via my controller. There are situations where I want to pass in a null value, but I do not want an error thrown when this happens. What should I change my code to?

最初我的代码是:

@foreach (var item in Model.MyModelStuff)
{
    <tr>
        <td>
                @Html.DisplayFor(modelItem => item.Bla.Title)
        </td>
    <tr>
}

我尝试了以下失败的尝试:

I have tried the following with no success:

@foreach (var item in Model.MyModelStuff.Where( item => item.MyModelStuff != null))
etc. . . 

如何更改代码,使其在不引发错误的情况下处理null?我已经读过我可能需要返回模型的空集合(?),如果确实需要这样做,我将如何去做?

How do I change the code so that it will handle null without throwing an error? I've read I may need to be returning an empty collection of my model (?), how would I go about doing that - if it is indeed the necessary thing to do?

推荐答案

如果我的理解正确,则您的收藏集为空.

If my understanding is correct your collection is null.

集合永远不能为空,就像您说过的那样,您应该返回一个空集合,并防止您的集合被破坏而不暴露真实集合:

A collection should never be null, like you said you should return an empty collection instead and prevent your collection to be corrupted not exposing the real collection:

public IList<Employee> Employees
{
    get; 
    private set;
}

并在构造函数中初始化您的集合

And initialize your collection inside the constructor

this.Employees = new List<Employee>();

这篇关于当我的模型为null时,如何避免View的foreach循环中出现NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆