我正在使用 Razor 视图的 MVC。在这个特定的视图中,我传递了类 Bed
的一个实例。 Bed
有一个属性 string Infection
。现在,在这个实例中,我有一个布尔值 HasInfection
在视图中定义,我将在其他地方使用它来改变显示内容。最初它声明为
var HasInfection = (Model.Infection.Trim() != "";
并且按预期工作。然而,现在存在这样一种情况,即 Bed
可能为空。以下是第一个代码块:
@{
ViewBag.Title = "Edit";
var HasInfection = false;
if (Model != null)
{
HasInfection = Model.Infection.Trim() != "";
} // I get a NRE on this line whenever Model is null
}
我甚至尝试了复杂的嵌套if-else解决方案,但在if
的闭合括号处仍然遇到了NRE错误。
if (Model.Infection == null)
{
HasInfection = false;
}
else
{
if (Model.Infection != "")
{
HasInfection = true;
}
else
{
HasInfection = false;
}
}
我已经尝试了所有的 &/&&/|/|| 的组合,但都没有成功。如果Model为空或者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);
}
var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection);
上遇到了异常。在编辑之前,它出现在任何if
语句的闭合括号上。 - Phillip Copley_b
不为空并且result
不为空吗? - Tallmaris