當我在控制器中執行自定義錯誤處理時,我無法通過重定向同一頁面來保留原始資料。假設我有一個網頁呼叫 Create.cshtml。在那個創建網頁中,我有一些表單控制元件需要用戶輸入類代碼,但類代碼不能重復。假設用戶輸入了系統中存在的類代碼,我的系統應該重定向回 Create.cshtml 并傳遞錯誤訊息(例如 ViewBag.error = "Class Code duplicated")并同時傳遞。但是我當前的實作在重定向后不會恢復原始內容/資料。
類控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([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"] = "This class code has been existed in the system";
ModelState.AddModelError("error", "This class code has been existed in the system");
return RedirectToAction(nameof(Create),@class);
}
_context.Add(@class);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(@class);
}
創建.cshtml
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ClassCode" class="control-label"></label>
<input asp-for="ClassCode" class="form-control" />
<span asp-validation-for="ClassCode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ClassName" class="control-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">
<label class="control-label">@TempData["error"]</label>
</div>
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
系統環境:.NET Core Entity Framework
uj5u.com熱心網友回復:
使用重定向時,應使用 TempData 而不是 ViewBag。
TempData["error"] = "This class code has been existed in the system";
return RedirectToAction(nameof(Create));
你被重定向到createget方法,如果它不回傳模型,資料會丟失,我想你可以直接return View()在這里。
if (cls != null)
{
TempData["error"] = "This class code has been existed in the system";
ModelState.AddModelError("error", "This class code has been existed in the system");
return View(nameof(Create), @class);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415876.html
標籤:
