Ecnalyr
Ecnalyr

Reputation: 5802

How does one avoid a NullReferenceException in a foreach loop within a View when my model is null?

I get a "NullReferenceException was unhandled by user code" error with the following code in my View when I pass in a null value via my controller. There are situations where I want to pass in a null value, but I do not want an error thrown when this happens. What should I change my code to?

Originally my code was:

@foreach (var item in Model.MyModelStuff)
{
    <tr>
        <td>
                @Html.DisplayFor(modelItem => item.Bla.Title)
        </td>
    <tr>
}

I have tried the following with no success:

@foreach (var item in Model.MyModelStuff.Where( item => item.MyModelStuff != null))
etc. . . 

How do I change the code so that it will handle null without throwing an error? I've read I may need to be returning an empty collection of my model (?), how would I go about doing that - if it is indeed the necessary thing to do?

Upvotes: 5

Views: 13194

Answers (2)

Jupaol
Jupaol

Reputation: 21365

If my understanding is correct your collection is null.

A collection should never be null, like you said you should return an empty collection instead and prevent your collection to be corrupted not exposing the real collection:

public IList<Employee> Employees
{
    get; 
    private set;
}

And initialize your collection inside the constructor

this.Employees = new List<Employee>();

Upvotes: 8

Kirk Woll
Kirk Woll

Reputation: 77546

Honestly, I think a null model is a poor choice. But if you insist, just add an if check:

@if (Model != null) {
    foreach (var item in Model.MyModelStuff)
    {
        <tr>
            <td>
                    @Html.DisplayFor(modelItem => item.Bla.Title)
            </td>
        <tr>
    }
}

Upvotes: 7

Related Questions