我构建了一个编辑页面来更新数据,如果传递了正确的ID但传入的ID无效时,它会正常工作我得到一个空引用异常。我知道这是由于LINQ查询没有从数据库中找到任何有效数据的事实,但我不知道如何处理这个,除非我在我的视图中添加一堆IF
语句,以便每次引用模型。这是我目前拥有的控制器代码。如果在模型的LINQ查询中找不到任何结果,则返回错误消息
public ActionResult EditSection(Int16 id = -1)
{
Section section = db.Sections.Find(id);
SectionAddEditVM model = new SectionAddEditVM { Section = section };
if (section != null)
{
if (section.Type == "Collection")
{
RedirectToAction("Collection", new { id = id });
}
model.SelectedType = section.Type;
return View(model);
}
ModelState.AddModelError("Section ID", "Invalid Section ID");
return View(model);
}
查看:
@model SectionAddEditVM
@{
ViewBag.Title = "Edit " + Model.Section.Title + " Information";
}
<h2>
Edit @Model.Section.Title Information
</h2>
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken();
@Html.ValidationSummary(false)
<p>
@Html.HiddenFor(m => m.Section.ID)
<label for="Title">Seciton Title:</label> @Html.EditorFor(m => m.Section.Title)
<br />
<label for="RouteName">Section Route:</label> @Html.EditorFor(m => m.Section.RouteName)
<br />
<label for="Type">Section Type:</label> @Html.DropDownListFor(m => m.Section.Type, new SelectList(Model.Type, "Value", "Text"))
<br />
@Html.HiddenFor(m => m.Section.LogoFileID)
<label for="LogoFile">Logo Image:</label> <input id="LogoFile" name="LogoFile" type="file" />
<br />
<label for="Synopsis">Synopsis:</label> @Html.EditorFor(m => m.Section.Synopsis)
<br />
<input type="submit" value="Edit Information" />
</p>
}
null参考异常在上面的代码中发生了什么?在新的SectionAddEditVM?或者你已经用if(section!= null)来解释它 – tofutim
当我参考模型时,空引用异常发生在视图中。我添加了视图代码以供参考。 – Matthew
为什么在视图中需要很多if语句?一个if语句会处理这个......'if(model == null){output message} else {do stuff}。或者,而不是模型状态错误,重定向到基本上说您的请求包含无效数据的错误视图。 – Tommy