Patrik Gustafsson
Patrik Gustafsson

Reputation: 198

Returning a view from a helper class in Mvc 5

I have a try - catch segment in a helper class. I want to return a view if the try catch segment throws an error. Now I have:

try
{
    //some code
}
catch (Exception ex)
{
    return View("~/Views/Home/Index.cshtml");
}

Upvotes: 0

Views: 1003

Answers (2)

Remay
Remay

Reputation: 69

Try this :

try
{

}
catch (System.Exception)
{
    return RedirectToAction("Index", "Home");
}

Upvotes: 0

Peter B
Peter B

Reputation: 24147

There are two ways:
1. (Re)throw the exception in the helper + add exception handling to the controller, or
2. Catch exception in the helper, return e.g. a bool to signal success/failure + respond to this value in the controller.

1st approach:

MyController.cs

public ActionResult Index()
{
    try
    {
        MyHelper.SomeMethod(); // This method is allowed to throw
        return View(); // No view name specified means this renders "Index"
    }
    catch (Exception ex)
    {
        return View("Error");
    }
}

2nd approach:

MyController.cs

public ActionResult Index()
{
    bool succeeded = MyHelper.SomeFunction(); // This method should never throw
    if (succeeded)
        return View(); // No view name specified means this renders "Index"
    else
        return View("Error");
}

Also, try to avoid calling helpers in your View, unless your View can handle all their results. When a View is already executing you can't simply 'switch' it to another view, that would be the task and the responsibility of the Controller.

Upvotes: 2

Related Questions