我正在使用MVC和Razor视图。在这个特定的视图中,我传递了一个类Bed
的单个实例。 Bed
有一个属性string Infection
。现在在这个例子中,我在视图中定义了一个布尔值HasInfection
,我在其他地方使用它来更改显示内容。这最初被宣布为NullReferenceException关闭时如果大括号
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
是null
或Model.Infection == ""
,HasInfection
应该是false
。
我在做什么错?
编辑
试图var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection);
后(因为Infection
可能是““),我仍然得到一个NullReferenceException。即使在View中出现异常,是否有可能在Controller中出现问题?
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);
}
那一行,你得到空的异常? – cederlof
@WillDean我已经尝试过在这一点上的一切组合,只是试图让一些工作。现在的编辑就是当前的代码。 @cederlof我在'var HasInfection = Model!= null &&!string.IsNullOrWhiteSpace(Model.Infection);'now'上得到异常。在编辑之前,它是在任何'if'语句的大括号之前。 –
野猜这里...是BedModel数据库相关?如果它是一个IQueryable,那么有可能在你第一次使用它时调用“实际”查询......你是否尝试过在控制器中进行调试,以检查'_b'是否为空,并且'result'不为空? – Tallmaris