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?
File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .
AJAX is used to create dynamic web pages that do not require page reloading when any part of the whole web page content or the whole web page content is changed. The server data exchange is asynchronous in nature and AJAX in ASP.net uses multiple technologies like XSLT, XHTML, CSS, JavaScript, etc.
Uploading Files in MVC using jQuery AJAX FormDataGo to File->New->Project. Give a suitable name to the Application. Click OK. As you can see in the above image, two files are sent to C# ActionMethod, and both will be uploaded now.
We cannot download the file through Ajax, must use XMLHttpRequest.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With