KentZhou
KentZhou

Reputation: 25553

How to redirect to error page in view in MS ASP.NET MVC?

In Controller, RedirectToAction("Error") can redirect to error page. How to write code in view code to allow the page redirected to error.aspx view?

Upvotes: 0

Views: 4289

Answers (2)

Keith
Keith

Reputation: 155652

You shouldn't need to handle reporting of errors inside MVC actions, and hard coding error behaviour makes finding a fixing issues harder than it needs to be.

Instead use the HandleError attribute and throw a regular exception:

[HandleError]
public class ThingController : Controller 
{
    public ActionResult DoStuff()
    {
        ...

        // uh-oh! throw exception
        throw new WhateverException("message");
    }
}

This will allow you to use the customErrors config flag to change your application's behaviour:

<customErrors mode="RemoteOnly" defaultRedirect="~/System/Error" />

Then locally you'll get an ugly but detailed yellow screen of death, plus debug will break on the thrown exception by default.

Remote users will get redirected to your SystemController.Error where you can have a nice user-friendly message and log the error.

This will work for controller actions and views in the same way.

Upvotes: 2

CoderDennis
CoderDennis

Reputation: 13837

@Jørn is right, but what kinds of errors are you predicting to show up in your view?

If you gave some details on why you're thinking about this, we might be able to suggest some better alternatives instead of simply saying "don't do this."

Upvotes: 0

Related Questions