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)?