在视图中检查null时,为什么会出现NullReferenceException

Dan*_*ous 2 c# asp.net-mvc-3

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

查看型号:

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

public class AccountsViewModel
{
    public List<string> Accounts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

视图:

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


    ...
}
Run Code Online (Sandbox Code Playgroud)

一切都编译得很好但是当我运行页面时,我得到一个NullReferenceException was unhandled在线:

@if (Model.Accounts != null)
Run Code Online (Sandbox Code Playgroud)

为什么我在检查空引用时获得空引用异常?我错过了什么?

fix*_*gon 10

因为Modelnull而不是财产Accounts.

您也应该检查是否Model null

例:

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

}
Run Code Online (Sandbox Code Playgroud)