How could I handle an asp.net mvc error AND use the same view from the controller?
I have actions like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(Product product)
{
try
{
if(ModelState.IsValid)
{
_productService.Create(product);
TempData["success"] = "Product created successfully!";
return RedirectToAction("Edit", new { product.Id });
}
}
catch (Exception e)
{
Logger.Exception(e);
TempData["error"] = "Oops, an error occurred! Please try again in a few moments.";
}
return View(product);
}
I want to take this error handling logic out of the methods. However, instead of the default [HandleError] way of doing things, instead of redirecting the user to another view in case of an error, it returns me the same view with a TempData["error"], and a notification will appear in the top of the same page.
How could I do this, delete all th开发者_C百科is try{}catch{} code and put this logic outside this action, for other actions as well?
You should be able to use [HandleError] and OnException to do what you want. Eg, to display a custom view:
protected override void OnException(ExceptionContext filterContext)
{
// Output a nice error page
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
I posted a little more info about this on my blog a while back:
http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html
精彩评论