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" ></div>
<div >
<label asp-for="ClassCode" ></label>
<input asp-for="ClassCode" />
<span asp-validation-for="ClassCode" ></span>
</div>
<div >
<label asp-for="ClassName" ></label>
<input asp-for="ClassName" />
<span asp-validation-for="ClassName" ></span>
</div>
@if (@TempData["error"] != null)
{
<div >
<label >@TempData["error"]</label>
</div>
}
<div >
<input type="submit" value="Create" />
</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);
}
