如果在linq查询模型中找不到结果,则返回错误消息
-
21-12-2019 - |
题
我建立了一个编辑页面来更新数据,如果传入正确的ID,它可以正常工作,但是当传入无效的ID时,我得到一个空引用异常。我知道这是由于LINQ查询没有从数据库中找到任何有效的数据,但我不确定如何处理这个,除非我添加了一堆 IF
每次引用模型时,在我的视图中检查null的语句。这是我目前拥有的控制器的代码。
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>
}
解决方案 2
解决方案是添加一个生成的ELSE
子句并初始化新的空白模型。
public ActionResult EditSection(Int16 id = -1)
{
Section section = db.Sections.Find(id);
if (section != null)
{
if (section.Type == "Collection")
{
RedirectToAction("Collection", new { id = id });
}
SectionAddEditVM model = new SectionAddEditVM { Section = section };
model.SelectedType = section.Type;
return View(model);
}
else
{
section = new Section();
SectionAddEditVM model = new SectionAddEditVM { Section = section };
ModelState.AddModelError("Section ID", "Invalid Section ID");
return View(model);
}
}
. 其他提示
在你的控制器中,你已经在检查是否 section
是 null
.所以,万一是这样的话 null
只是返回一个不同的观点,说:"没有找到部分"之类的。另外(正如@Aron在这里建议的那样)你可以返回 404
状态代码与此视图,所以控制器看起来像这样:
// find section based on ID
// ... actual code ...
if (section != null)
{
// process data and assign to model
return View(model);
}
else
{
Response.StatusCode = (int) System.Net.HttpStatusCode.NotFound;
return View("NoSectionFound");
}
请注意,通过返回不同的视图,您不会返回不同的页面。URL仍然是相同的,因为它基于控制器而不是视图。通过呈现不同的视图,您可以避免在通常显示数据的视图中使代码复杂化。
顺便说一句,避免提供"太多"的信息,如"无效的部分ID",这可能会将潜在的攻击者引导到下一步"戳"的位置。
我也会重新排列代码,这样你就可以为 model
只有当找到section并且对于"no section found"视图,您显然不需要传递任何模型。
不隶属于 StackOverflow