An Issue with [HandleError] attribute in MVC and JQuery Ajax Load()

September 10, 2008 04:59 by ndibek

In CTP release 4 of MVC frameowrk for Asp.Net we have seen an introduction of [HandleError] attribute that can be assigned to a Controller class or individual Action methods.  It works great.  It captures any unhandled exceptions thrown by your code, and redirects to the default error Handling page/view Error.aspx that displays the exception detail.

The behavior can be fine-tuned further to have different pages for different exception types, or different Action methods.  But I have found one scenario where this attribute does not work, but could easiuly be addressed.

 Lets imagine a scenario where lets say you are builing a wizard.  Your primary view gets loaded as a container for wizard pages, and then you want each of your actual pages to be loaded inside a panel on your wizard.  Obviously you want to avoid post-backs, and you want to load those wizard pages as Ahax loaded partials.

In other words, Ajax call invokes a call on your controller that renders the Html for your page, and then your Ajax/JScript libary inserts that HTML at pre-destined place on your page.  Simple.

 Except that for this case, when error hapens inside the Controller that reneders my partial page I get nothing - no expected page and no error page either.  So what is the problem? Take a look at the source code of the HandleErrorAttribute.OnException() method (I used Reflector to get to it):

 

 
As you can see in the last 2 lines we clear the existing Response stream and return a StatusCode of 500.  Ajax libraries, like the one I used - JQuery, assume that the 500 is "Internal Server Error", and do not load/get the actual Html.
 
Solution to this problem:  I built my own HandleErrorAjaxPartial that inherits from HandleError and overrides the OnException() method, calling the base.OnException() and resetting StatusCode to OK (instead of 500).  Then all of the Controller actions that render wizard pages and are called from my Ajax code got marked with this new attribute, and now everything is fine.
 
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading