當我的自定義錯誤處理在控制器中執行時,我很難通過重定向同一頁面來保留原始資料。 假設我有一個叫Create.cshtml的網頁。 在該創建網頁中,我有幾個表單控制元件,需要用戶輸入類代碼,但類代碼不能被復制。 假設用戶輸入的類代碼在系統中已經存在,我的系統應該重定向到Create.cshtml并傳遞錯誤資訊(如ViewBag.error = "Class Code duplicated")并模擬。 但我目前的實作并沒有在重定向后恢復原來的內容/資料,
。ClassController:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task< IActionResult> 創建([Bind("ID、ClassCode、ClassName、DateCreation、DegreeID、CourseChapterID")] Class @class)。
{
if (ModelState.IsValid)
{
Class cls = await _context.Class.SingleOrDefaultAsync(c => c.ClassCode == @class.ClassCode) 。
if (cls != null)
{
TempData["error"] = "該類代碼已存在于系統中"。
ModelState.AddModelError("error", "這個類的代碼已經存在于系統中")。
return RedirectToAction(nameof(Create),@class)。
}
_context.Add(@class)。
await _context.SaveChangesAsync()。
return RedirectToAction(nameof(Index))。
}
return View(@class)。
}
Create.cshtml
<form asp-action="create">
<div asp-validation-summary="ModelOnly" class="text-danger"> < /div>
<div class="form-group">
<標簽asp-for="ClassCode" class="controll-label"> </label>
<input asp-for="ClassCode" class="form-control" />
<span asp-validation-for="ClassCode" class="text-danger"> </span>
</div>
<div class="form-group">
<標簽asp-for="ClassName" class="controll-label"> </label>
<input asp-for="ClassName" class="form-control" />
<span asp-validation-for="ClassName" class="text-danger"> </span>
</div>
@if (@TempData["error"] != null)
{
<div class="form-group">
<標簽 class="control-label">@TempData["error"]</label>
</div>
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
系統環境:.NET核心物體框架
uj5u.com熱心網友回復:
當你使用重定向時,你應該使用TempData而不是ViewBag。
TempData["error"] = "該類代碼已經存在于系統中"。
return RedirectToAction(nameof(Create));
你被重定向到create的get方法,如果它不回傳模型,資料就會丟失,我想你可以在這里直接回傳View()。
if (cls != null)
{
TempData["error"] = "該類代碼已存在于系統中"。
ModelState.AddModelError("error", "這個類的代碼已經存在于系統中")。
return View(nameof(Create), @class)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/320339.html
標籤:
上一篇:numpy.resize(image,(IMG_HEIGHT,IMG_WIDTH,3))中的3是什么?
下一篇:沒有'IEnumerable<SelectListItem>'型別的ViewData專案具有'ddlcontent'鍵。
