モデルのLINQクエリに結果が見つからない場合はエラーメッセージを返す
-
21-12-2019 - |
質問
私はデータを更新するための編集ページを構築し、正しいIDが渡されたが無効なIDが渡されたときには問題がありますが、NULLの参照例外を取得します。これは、LINQクエリがデータベースから有効なデータを見つけられないという事実が原因であることを知っていますが、私が参照するたびにNULLをチェックするためにIF
ステートメントの束を追加しない限り、これに対処する方法はわかりません。モデルこれが現在コントローラに持っているコードです。
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はまだ同じです。別のビューをレンダリングすることによって、通常はデータを表示するビュー内のコードを複雑にする必要がありません。
BTW、「無効なセクションID」のような情報を「Poke」に向けることができる情報のような情報を「Poke」にすることができる情報を「Poke」にすることができます。
またコードを並べ替えるので、セクションが見つかった場合にのみ値を割り当てて、「No Section」ビューを表示してください。
を渡す必要はありません。所属していません StackOverflow