1

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!

7
  • it looks like the object "item" is null. Can you show us where you initialize that object? Commented Oct 12, 2014 at 12:41
  • I've added to the original post Commented Oct 12, 2014 at 12:46
  • have you added "@model IList<TypeOfYourModel>" in your view? (As described here: weblogs.asp.net/scottgu/…) Commented Oct 12, 2014 at 12:58
  • I'd assume it's already implict as the information is already on the page and it works and populates, I just want to do some logic surrounding it with the if? Commented Oct 12, 2014 at 13:02
  • can you show us the whole page? Might be easier to see the problem then. Commented Oct 12, 2014 at 13:05

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.