No matter what I research, everything seems to point back to using the ASP.NET Core middleware to redirect to a specific error page. Does anyone have any ideas on how to handle exceptions, but keep the user on the same view?
For a Razor Pages application (which is typically a controller-less alternative to MVC) if you want to avoid middleware and redirecting to another page on an exception, then you need to handle the exception on this page, which means you have to use a try-catch statement where you catch the exception and set whatever message you want to display:
You'll need to adjust your .cshtml.cs method as follows:
public async Task<IActionResult> OnPostEditAsync(ViewModel vm) {
if (!ModelState.IsValid) {
return Page();
}
try {
m_oToolsService.SaveData(vm);
}
catch (Exception) {
ViewData["ExceptionMsg"] = "Friendly exception message";
return Page();
}
}
and to get the friendly exception message to display in a div on your .cshtml page:
<div>@ViewData["ExceptionMsg"]</div>