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?

4
  • 2
    Just to make sure, Model != null, right? Commented Oct 13, 2011 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. Commented Oct 13, 2011 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.. Commented Oct 13, 2011 at 14:19
  • See stackoverflow.com/questions/4660142/… Commented Oct 13, 2011 at 14:19

4 Answers 4

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)
{

}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Model != null && Model.Accounts != null

Comments

2

Your model is probably null

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.