모델에 대한 LINQ 쿼리에서 결과가 없으면 오류 메시지를 반환합니다.
-
21-12-2019 - |
문제
i 편집 페이지를 만들어 데이터를 업데이트하고 올바른 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, 잠재적 인 공격자가 다음에 "poke"를 어디에 보낼 수있는 "잘못된 섹션 ID"와 같은 "너무 많은"정보를 제공하지 마십시오.
코드를 재정렬하여 섹션을 찾을 때만 model
에 값을 할당하고 "no section found no pender"를 볼 수있는 경우에만 값을 지정하십시오.