I was wondering what the best implementation for a global error (doesn’t have to be errors, can also be success messages) handler would be? Let me break it down for you with an example:
- User tries to delete a record
- Deletion fails and an error is logged
- User redirects to another page
- Display error message for user (using a HtmlHelper or something, don’t want it to be a specific error page)
I’m just curious what you guys think. I’ve been considering TempData, ViewData and Session but they all have their pros and cons.
TIA!
UPDATE:
I’ll show an example what I exactly mean, maybe I wasn’t clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page
public ActionResult DeleteRecord(Record recordToDelete)
{
// If user succeeds deleting the record
if (_service.DeleteRecord(recordToDelete)
{
// Add success message
MessageHandler.AddMessage(Status.SUCCESS, "A message to user");
// And redirect to list view
return RedirectToAction("RecordsList");
}
else
{
// Else return records details view
return View("RecordDetails", recordToDelete);
}
}
And in the view “RecordsList”, it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.
<%= Html.RenderAllMessages %>
This can be achieved in many ways, I’m just curious what you guys would do.
UPDATE 2:
I have created a custom error (message) handler. You can see the code if you scroll down.
I’m confused by these steps:
Why would you redirect the User when an error occurs? That doesnt make any sense, unless im misunderstanding something.
Generally, i follow these guidelines:
ModelState.IsValidand return the same View and render the error out with@Html.ValidationSummary()JsonResult(like @Tomas says), and use basic client-side scripting to inspect the JSON and show the resultModelStateas above