Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
Ecnalyr Avatar asked Apr 28 '12 00:04

Ecnalyr


People also ask

How to solve null reference exception?

You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.

Does for each loop check for null?

The question checks if the collection is null first before doing the for-each. Your link checks if the item in the collection is null.

What does NullReferenceException object reference not set to an instance of an object?

The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these: Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)

What is a null reference error?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .

What is a nullreferenceexception?

How to handle C# NullReferenceException? Examples How to handle C# NullReferenceException? Examples NullReferenceException is thrown in C# when you try to access a property of method on an object of null reference. Hence the name Null Reference. Simply put, the object is null. The object here could be a string, a class object, or anything.

How to prevent the nullreferenceexception in displaycities()?

If the caller of the DisplayCities () function pass a null IList value then it will raise a NullReferenceException. To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them.

Why does my model variable point to null when rendering a view?

That’s why when the view is being rendered, Model variable inside of .cshtml points to null, and trying to access null.FirstName obviously throws a brand spanking new NullReferenceException. To fix this need to pass an instance of the model to the View () call:

What happens when you call a function on a null reference?

Similarly, calling any functions on a null reference will result in NullReferenceException. Say you are building an auction site, where users can add photos to their listings. There’s class called ‘Listing’ that has a collection of ‘Photos’, and you want users to be able to submit new listings along with the photos in the following manner:


2 Answers

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>();
like image 94
Jupaol Avatar answered Oct 16 '22 03:10

Jupaol


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>
    }
}
like image 42
Kirk Woll Avatar answered Oct 16 '22 03:10

Kirk Woll