Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在视图中检查null时会出现null引用异常_C#_Asp.net Mvc 3 - Fatal编程技术网

C# 为什么在视图中检查null时会出现null引用异常

C# 为什么在视图中检查null时会出现null引用异常,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我有以下代码向用户显示帐号列表 查看模型: @model AccountsViewModel using (@Html.BeginForm()) { <ul> @*if there are accounts in the account list*@ @if (Model.Accounts != null) { foreach (string account in Model.Accounts)

我有以下代码向用户显示帐号列表

查看模型:

@model AccountsViewModel

using (@Html.BeginForm())
{
    <ul>
        @*if there are accounts in the account list*@
        @if (Model.Accounts != null)
        {
            foreach (string account in Model.Accounts)
            {
                <li>Account number* <input type="text" name="account" value="@account"/></li>
            }
        }

        @*display an additional blank text field for the user to add an additional account number*@
        <li>Account number* <input type="text" name="account"/></li>

    </ul>


    ...
}
有时该列表将为空,因为没有要显示的帐户

public class AccountsViewModel
{
    public List<string> Accounts { get; set; }
}

为什么在检查空引用时会出现空引用异常?我缺少什么?

因为
模型
而不是属性
帐户

您还应该检查
模型
是否为

@if (Model != null && Model.Accounts != null)
例子:
您的模型可能是
null

@if (Model != null && Model.Accounts != null)

显然,
Model
为空,您必须将条件更改为

Model != null && Model.Accounts != null

在没有看到Action方法的情况下,我假设您的模型为null(这是您在该行中获得该错误的唯一方法)。只需要一张额外的支票:

if(Model != null && Model.Accounts != null)

只是为了确保,
Model!=null
,对吗?我认为@ZachJohnson做到了,但将任何类型的集合默认为空集也是标准做法。它为您省去了每次使用时都要测试null的麻烦。OffTopic:Model.Accounts!=null并不是真正检查列表中是否没有任何account对象。。它检查列表本身是否为空。请参阅
if(Model != null && Model.Accounts != null)