I have the following code to display a list of account numbers to the user.
View Model:
Sometimes the list will be null as there will be no accounts to display.
public class AccountsViewModel
{
public List<string> Accounts { get; set; }
}
View:
@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>
...
}
Everything compiles fine but when I run the page I get a NullReferenceException was unhandled
at the line:
@if (Model.Accounts != null)
Why am I getting a null reference exception on a check for a null reference? What am I missing?