I am using a rescue derived from MvcContrib:
public class RescueAttribute : MvcContrib.Filters.RescueAttribute
{
public RescueAttribute(string view) : base(view)
{
IgnoreAjax = false;
}
public RescueAttribute(string view, params Type[] exceptionTypes) : base(view, exceptionTypes)
{
IgnoreAjax = false;
}
protected override ActionResult CreateActionResult(Exception exception, ExceptionContext context)
{
var controller = (string) context.RouteData.Values["controller"];
var action = (string) context.RouteData.Values["action"];
var model = new HandleErrorInfo(exception, controller, action);
if (context.Controller.ControllerContext.HttpContext.Request.IsAjaxRequest())
{
return new JsonResult(model);
}
return base.CreateActionResult(exception, context);
}
}
Now when using the file upload in jQuery.form, Request.IsAjaxRequest() returns false. Apparently this is because you can’t actually upload a file using json; this plugin generates a hidden iframe to do the upload.
To compensate I am appending a hidden input to any form that is submitted with jquery.form and has file inputs:
$(this).append('<input type="hidden" name="X-Requested-With" value="XMLHttpRequest" />');
It’s good enough to fool IsAjaxRequest. Is there any reason why I shouldn’t do this?
This method is fine.
JQuery and other client libraries put X-Requested-With in the headers. However, the ASP Ajax helpers use hidden form elements just as you did above.
The important thing is that IsAjaxRequest() checks both form fields and headers. So if it finds XMLHttpRequest for X-Requested-With in either place, it returns true.
Nice technique. I might use it one day.