NullReferenceException on close if bracket

I am using MVC with Razor views. In this particular view, I am passing one instance of a class Bed. Bedhas a property string Infection. Now in this case, I have a boolean HasInfectiondefined in the view that I use elsewhere to change what is displayed. It was originally announced as

var HasInfection = (Model.Infection.Trim() != "";

and worked properly. However, there is now a use case where it Bedcan be null. Here is the 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 even tried a convoluted if-else nested solution, and I still get the NRE in the closing bracket if.

if (Model.Infection == null)
{
    HasInfection = false;
}
else
{
    if (Model.Infection != "")
    {
        HasInfection = true;
    }
    else
    {
        HasInfection = false;
    }
}

&/&/|/|| . Model - null Model.Infection == "", HasInfection false.

?

var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection); ( Infection "), NullReferenceException. , , ?

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);
}
+4
4

.

, , 35 ( ), , NullReferenceException .

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
+4

- :

var HasInfection = Model != null && !String.IsNullOrWhitespace(Model.Infection)

, - Razor, , .

, , "NullBed", , "" , - , .

: , , - , . , , .

Edit2: , . , , StackOverflow... - "" , , , , .

Bed, , HasInfection Bed, , , . , BedStatus . , , , , , ( ) .

+2
HasInfection = Model != null && !string.IsNullOrWhitespace(Model.Infection);
+1

Model null , Model is not null, Model.Infection

:

if(Model != null && Model.Infection != null && Model.Infection.Trim() != "")
{
        HasInfection = true;
}
0

All Articles