Phi*_*ley 5 c# asp.net-mvc nullreferenceexception razor
我正在使用MVC和Razor视图.在这个特定的视图中,我传递的是该类的单个实例Bed.Bed有房产string Infection.现在在这个例子中,我HasInfection在视图中定义了一个布尔值,我在其他地方用它来改变显示的内容.这最初被宣布为
var HasInfection = (Model.Infection.Trim() != "";
Run Code Online (Sandbox Code Playgroud)
并按预期工作.但是,现在有一个用例Bed可能为null.这是第一个代码块:
@{
ViewBag.Title = "Edit";
var HasInfection = false;
if (Model != null)
{
HasInfection = Model.Infection.Trim() != "";
} // I get a NRE on this line whenever Model is null
}
Run Code Online (Sandbox Code Playgroud)
我甚至尝试过复杂的嵌套if-else解决方案,而且我仍然在结束时得到一个NRE if.
if (Model.Infection == null)
{
HasInfection = false;
}
else
{
if (Model.Infection != "")
{
HasInfection = true;
}
else
{
HasInfection = false;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了&/ &&/|/||的每个组合 我可以想到没有成功.如果Model是null或Model.Infection == "",HasInfection应该是false.
我究竟做错了什么?
编辑
尝试后var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection);(因为Infection可能是""),我仍然得到一个NullReferenceException.即使异常在视图中,问题是否可能在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);
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题。
在查看此问题中的第二条评论时,我发现我的异常实际上比 NullReferenceException 指向的右括号更远了 35 行(括号外)。
例如:
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
Run Code Online (Sandbox Code Playgroud)
HasInfection = Model != null && !string.IsNullOrWhitespace(Model.Infection);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1369 次 |
| 最近记录: |