gpt4 book ai didi

c# - 为什么在 View 中检查 null 时会出现 NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 18:55:08 25 4
gpt4 key购买 nike

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

查看模型:

有时列表将为空,因为没有可显示的帐户。

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

查看:

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


...
}

一切都可以正常编译,但是当我运行该页面时,我在该行得到了一个NullReferenceException was unhandled:

@if (Model.Accounts != null)

为什么我在检查空引用时会收到空引用异常?我错过了什么?

最佳答案

因为 Modelnull 而不是属性 Accounts

您还应该检查 Model 是否 null

示例:

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

}

关于c# - 为什么在 View 中检查 null 时会出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com