Post updated to reflect partial fix suggested by @Kate. Original post below new post:
I have Ajax call to HttpPost Action method. If the method executes without exception, I want it load its data as a partial view in a div element (it does this successfully). If there is an exception, I want it to load the asp mvc Error view as a full page view. However, with the code below, an exception causes the Error view to load as partial view in said div element. I must be leaving something out of my controller…
[HttpPost]
[HandleError]
public ActionResult LoadUnmappedProjects()
{
bool error = false;
try
{
throw new ArgumentException();
}
catch (Exception e)
{
error = true;
}
if (!error)
using (var db = new prismEntities())
{
return PartialView(db.dmPSPProjectStatewideRegionals.ToList());
}
else
{
return View("Error");
}
}
Ideas???
ORIGINAL POST
In an ASP MVC3 web app, I have an ajax call to and [HttpPost] action method. The method hits a database and return data to a partial view. If the database or the table of interest is down, I’d like to return the Error view. But I can’t seem to combine [HttpPost] and [HandleError] on the method to effect this:
[HttpPost]
[HandleError]
public ActionResult LoadUnmappedProjects()
{
try
{
throw new ArgumentException();
}
catch (Exception e)
{
throw new CustomDbException(e);
}
using (var db = new prismEntities()){
return PartialView(db.dmPSPProjectStatewideRegionals.ToList());
}
}
The stock Error.cshtml doesn’t get rendered. Instead, an error gets returned to the Ajax call, and currently I’m just popping up an alert(). Is there some thing I can do to the method above to cause the Error view to render? Or should I use the error returned in the Ajax call to somehow render the Error view?
Here is my ajax call:
$.ajax({
url: pathLoadUnmappedProjects,
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#unmappedProjects').html(result);
},
error: function () {
alert("Error:");
}
});
The problem is in your code. Because you throw the exception it automatically stop the process and return 500 Error server (you can check the Net tab in your Firebug to see it). So, my suggestion is not to throw exception here:
If you need to redirect to some page just try to return the page name what you want to redirect to and do it in JS code as described here: How to reload page when an ajax request returns FormsAuthentication.RedirectToLoginPage?
So you code will looks like:
In this case you can throw exception as you did before and the ajax code will catch error response and redirect.