2

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?

Dangerous
  • 4,590
  • 3
  • 29
  • 47
  • 2
    Just to make sure, `Model != null`, right? – Zach Johnson Oct 13 '11 at 14:17
  • 2
    I think @ZachJohnson hit it, but also it's standard practice to make any kind of collection default to an empty set. It saves you headaches down the road and from testing null with every use. – Brad Christie Oct 13 '11 at 14:18
  • OffTopic: Model.Accounts != null isn't really checking if there arent any account object in the list.. It checks if the list itself is null.. – Rob Oct 13 '11 at 14:19
  • See http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net – John Saunders Oct 13 '11 at 14:19

4 Answers4

10

because Model is null and not the property Accounts.

You should check also if Model is not null

Example:

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

}
Binarian
  • 11,710
  • 8
  • 50
  • 82
fixagon
  • 5,336
  • 19
  • 25
3

Obviously Model is null, you've to change condition to

Model != null && Model.Accounts != null
sll
  • 56,967
  • 21
  • 100
  • 149
2

Your model is probably null

@if (Model != null && Model.Accounts != null)
hunter
  • 58,834
  • 17
  • 108
  • 112
1

Without seeing the Action method, I'm assuming your Model is null (which is the only way you would get that error on that line). Just need an extra check:

if(Model != null && Model.Accounts != null)
Justin Niessner
  • 229,755
  • 35
  • 391
  • 521