5

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?

2 Answers 2

8

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>();
Sign up to request clarification or add additional context in comments.

Comments

7

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>
    }
}

2 Comments

Ok, that fixes it just fine. What is a better solution - I am allowing users to view a list of their Courses (think of a school) - if they don't have courses their course list is null - what should I do in it's stead?
What about returning a valid (non-null) model, but instantiating Model.MyModelStuff to an empty list/enumerable, rather than a null one? Then your view code simplifies nicely.

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.