ca9163d9
ca9163d9

Reputation: 29159

How to create an shared error message page?

In an Asp.Net Mvc 4 site, there may be various errors which error messages should be shown to end users (e.g. "Cannot find the row with ID of xxx.", "Cannot delete this row because it's xxx is depended on it.", ... etc).

How to (and what's the best approach) define a generic error page accept an error message and display it? Or maybe just a popup dialog box?

Upvotes: 1

Views: 107

Answers (4)

Igarioshka
Igarioshka

Reputation: 677

I would suggest creating a partial View, and a simple Error model. The view would be rendered in the layout. The error model may be then past as TempData, as it is deleted after first read. in the view, if you have the variable, in the TempData - you show the element with the necessary layout, otherwise - you don't show anything. As well, you may have an extension method on TempData to add the error.

Upvotes: 0

Amit
Amit

Reputation: 15387

Create a ErrorAction in Controller.

You can catch the error and redirect to ErrorAction with message. Show as you want.

I hope you understand my point.

Upvotes: 1

Kaarthik
Kaarthik

Reputation: 627

This is what we were doing in one of the projects I had worked on before. We had a div tag in our page where we would display all success and failure messages. The way it would work is as follows:

  1. We would get the message from the controller to the view via AJAX.
  2. Then we would inject that message into the div tag.
  3. We would switch html class of that div based on the success condition. If it was success in that case we would display the entire message in green with a tick else if it was an error we would display the entire message in red with a cross.Both the css classes were defined in our site.css.

I hope I have answered you question.

Upvotes: 0

Mediator
Mediator

Reputation: 15378

You could create CustomException and throw when him need. In global asax you must override Application_Error

protected void Application_Error(object sender, EventArgs e)
{
            Response.Clear();
            var httpContext = ((MvcApplication)sender).Context;
            var ex = Server.GetLastError();
            // check exception and redirect to your custom error page with Title, Description and url for redirect.
}

Upvotes: 1

Related Questions