Trinitrotoluene
Trinitrotoluene

Reputation: 1458

ASP.NET Razor Entity Framework Null reference exception

Here is the code that is causing the problem, it is inside the view:

@{
    if(item.Contract_Type != null)
    {
        dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
    }
}
<td @dangerhtml>
    @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

This code is sitting inside a foreach:

@foreach (var item in Model) {
..etc
}

It is throwing a NullReferenceException on the if line. The code works fine if I remove all the above and just do:

<td>
        @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

But I am looking to set the class for the cell based on the contents of the item.Contract_Type

Any help appreciated!

Upvotes: 1

Views: 859

Answers (1)

PzYon
PzYon

Reputation: 2993

I'm pretty sure that item is null, as Luke has already mentioned and that @Html.DisplayFor will just swallow this.

Why don't you just add following where clause to prevent null-items from being processed:

@foreach (var item in Model.Where(i => i != null))
{
  ..etc
}

Or you can null-check the item before checking the Contract_Type to prevent the NullReferenceException from occurring:

if(item != null && item.Contract_Type != null)
{
  dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
}

But maybe the best approach would be to ensure that no null-object is written to the Model-collection before passing it to the view..

Upvotes: 2

Related Questions