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)