我構建了一個編輯頁面來更新數據,如果傳遞了正確的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