0

I ran up against this error and I'm wondering if anyone can help explain why this is happening.
I'm displaying a list of books in a view and everything is displaying properly from the model. However, this code below isn't working:

@foreach (var item in Model.Books)
{
  .. (other unrelevant code is here)...
@{
<!-- Display icon based on the recommendation status -->     
if (item.Recommendation.recName == "Highly Recommended" || item.Recommendation.recName == "Recommended")
{
    <img src="~/Content/Images/check.png" alt="Recommended" title="This book is recommended."/>      
}

if (item.Recommendation.recName == "Parental Judgement")
{
    <img src="~/Content/Images/warning.png" alt="Parental Judgement" title="Parental Judgement required for this book."/>
}

if (item.Recommendation.recName == "NOT Recommended")
{
    <img src="~/Content/Images/stop.png" alt="Not Recommended" title="This book is NOT Recommended!"/>
}
}
.. (other unrelevant code is here)...
}

It should be pretty obvious from the code, but what I'm trying to do is display a different icon based on the recommendation status of each book. When I run that code, it gives me an error saying Object reference not set to an instance of an object.

This is a pretty standard type of error, but I'm confused because the object reference seems to be set, based on the fact that this code works properly and displays the proper value (such as Highly Recommended or Not recommended) for each book:
@Html.DisplayFor(modelItem => item.Recommendation.recName)

So to sum up my specific question: Why is the lambda expression in modelItem => item... working, while the other code for the same exact model isn't working?

And since I'm clearly missing an understanding of something here, let me ask the more general question for this: When is it "legal" to use the @item.property syntax, and when will it result in an error (like I have above)?

12
  • Where is item defined? Can you show that code? Also that lambda seems wrong, it'd expect item = > item.Recommedation.recName. Commented May 30, 2017 at 2:11
  • Have you sure item.Recommendation.recName exists? NRE means that each item or Recommendation part contains null value which can't be dereferenced (see NRE explanation here: stackoverflow.com/questions/4660142/…). Commented May 30, 2017 at 2:16
  • @juharr I added in the beginning of the foreach loop. Commented May 30, 2017 at 2:19
  • Why was the question marked down? And @TetsuyaYamamoto I understand what a NRE is, but @Html.DisplayFor(modelItem => item.Recommendation.recName) works. Doesn't that mean that the item or Recommendation both truly exists properly? Commented May 30, 2017 at 2:19
  • 1
    I don't know the controller method looks like, but often Model returns null due to not passing strongly-typed collection with return View(modelName). Note that ViewBag.Model is dynamic property, and potentially contains null value if model collection not returned properly. Model.Books.Recommendation probably uninitialized at this point and throwing NRE when dereferencing recName. Commented May 30, 2017 at 3:12

1 Answer 1

4

Null Reference Exception

Based on your description, the evidence points to your item.Recommendation type causing the null reference exception. It appears (without providing us with more information) that it is likely not initialized. Which may explain why your @Html.DisplayFor() is working.

You should consider checking if it is null first.

if(item.Recommendation == null) throw new Exception(" Whoops! :) ");

or on the alternative you could do a Safe Navigational / Null-conditional Operator

item.Recommendation?.recName // which does the work for you inline.

Side Note

I'm not a big fan of nesting / combining the use of @{ } razor code blocks inside other blocks. It can be difficult to read and usually a headache to debug.

@foreach ( ... )
{
    @{
        if( ... )
        {
            <html></html>
        }
    }
}

Versus

@{ var foo = null; } // appropriate for declaring variables, and clean blocks of code.

@foreach ( ... )
{
    @if( ... )
    {
        <html></html>
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The type is a string, so it didn't solve the issue. But I appreciate the tip about not the nesting the razor block. What you were saying makes a lot more sense now that it's written out with an example.
Yup, that did the trick! I got a Whoops :( but at least I know where to work from now. thank you Svek

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.