[英]Redirect back to Previous Page without losing original data
在 controller 中执行我的自定义错误处理时,我无法通过重定向同一页面来保留原始数据。 假设我有一个 web 页面调用 Create.cshtml。 在该创建网页中,我有一些表单控件需要用户输入 class 代码,但 class 代码不能重复。 假设用户输入了系统中存在的 class 代码,我的系统应该重定向回 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 核心实体框架
使用重定向时,应使用 TempData 而不是 ViewBag。
TempData["error"] = "This class code has been existed in the system";
return RedirectToAction(nameof(Create));
你重定向到create get
方法,如果它不返回model,数据会丢失,我想你可以在这里直接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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.