NullReferenceException on closing if brace
asp.net-mvc, c#, nullreferenceexception, razor
Solution
I had the same problem.
When looking to the second comment in this question I found out my exception was actually 35 lines further down the road (outside the brackets) than the closing bracket where the NullReferenceException pointed to.
For ex:
if(Model.Infection != null)
{
<p>Some Html</p>
} //given NullReferenceException location
<p>Model.Infection</p> //Actual cause of NullReferenceException since
//here Model.Infection can be null
Problem
I am using MVC with Razor views. In this particular view, I am passing a single instance of the class `Bed`. `Bed` has a property `string Infection`. Now in this instance, I have a boolean `HasInfection` defined in the view that I am using elsewhere to change what is displayed. This was originally declared as ``` var HasInfection = (Model.Infection.Trim() != ""; ``` and worked as expected. However, there is now a use case where `Bed` may be null. Here is that first block of code: ``` @{ ViewBag.Title = "Edit"; var HasInfection = false; if (Model != null) { HasInfection = Model.Infection.Trim() != ""; } // I get a NRE on this line whenever Model is null } ``` I have even tried the convoluted nested if-else solution, and I still get an NRE on the closing brace of `if`. ``` if (Model.Infection == null) { HasInfection = false; } else { if (Model.Infection != "") { HasInfection = true; } else { HasInfection = false; } } ``` I've tried every combination of &/&&/|/|| I can think of with no success. If `Model` is `null` or `Model.Infection == ""`, `HasInfection` should be `false`. What am I doing wrong? EDIT After attempting `var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection);` (since `Infection` could be " "), I still get a NullReferenceException. Is it possible the issue is in the Controller even if the exception is in the View? ``` public ActionResult EditReservation(int Facility, string Room, string Bed) { var BedModel = New Bed(); List<Bed> _b = BedModel.GetBed(Facility, Room, Bed); Bed result = _b.Where(bed => bed.BedStatus == "R" || bed.BedStatus == "A").FirstOrDefault(); return View("Edit", result); } ```