Dangerous
Dangerous

Reputation: 4909

Why do I get a NullReferenceException when checking for null in the view

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?

Upvotes: 2

Views: 4714

Answers (4)

fixagon
fixagon

Reputation: 5566

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

}

Upvotes: 10

Justin Niessner
Justin Niessner

Reputation: 245399

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)

Upvotes: 1

sll
sll

Reputation: 62484

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

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

Upvotes: 3

hunter
hunter

Reputation: 63512

Your model is probably null

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

Upvotes: 2

Related Questions