dotnet / dotnet/AspNetCore.Docs
Redirect After Adding a ModelState Error
- Dominant language
- C#
- Stars
- 13.1k
- Forks
- 24.6k
- Avg merge
- 1d 3h
- Merged PRs (30d)
- 97
Description
### Description
In the `EditPost` action method, the `DbUpdateException` is caught to add a ModelState error. To display this error to the user, the code should re-render the same Edit view. But the code redirects the user to the Index page. So the error is never displayed to the user.
```csharp
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task EditPost(int? id)
{
if (id == null)
{
return NotFound();
}
var courseToUpdate = await _context.Courses
.FirstOrDefaultAsync(c => c.CourseID == id);
if (await TryUpdateModelAsync(courseToUpdate,
"",
c => c.Credits, c => c.DepartmentID, c => c.Title))
{
try
{
await _context.SaveChangesAsync();
}
// ------------------------------------------------ Start Issue
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction(nameof(Index));
// ------------------------------------------------ End Issue
}
PopulateDepartmentsDropDownList(courseToUpdate.DepartmentID);
return View(courseToUpdate);
}
```
### Page URL
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/update-related-data?view=aspnetcore-8.0
### Content source URL
https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/data/ef-mvc/update-related-data.md
### Document ID
c06d8343-1407-aa05-de96-c1aca71ba232
### Article author
@tdykstra
[Related Issues](https://github.com/dotnet/AspNetCore.Docs/issues?q=is%3Aissue+is%3Aopen+c06d8343-1407-aa05-de96-c1aca71ba232)
Contributor guide
Assessment
This issue has not been assessed yet.