I have trouble preserving the original data by redirecting the same page when my custom error handling is executed in the controller. Assume that I have a web page call Create.cshtml. In that create webpage, I have a few form control which require the user to enter class code but the class code cannot be duplicated. Assume that the user entered a class code that is existed in the system, my system should redirect back to Create.cshtml and pass error message (E.g. ViewBag.error = "Class Code duplicated") and simulatenously . But my current implementation does not revert back the original content/data after redirect.
ClassController:
[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);
}
Create.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>
System environment: .NET Core Entity Framework
CodePudding user response:
When you use redirection, you should use TempData instead of ViewBag.
TempData["error"] = "This class code has been existed in the system";
return RedirectToAction(nameof(Create));
You are redirect to the create get method, if it doesn't return the model, the data will lose, I think you can directly return View() here.
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);
}
