Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricking ASP.NET into Thinking Request is Ajax Request for jQuery File Upload

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?

like image 791
João Bragança Avatar asked Aug 04 '10 17:08

João Bragança


People also ask

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .

Can AJAX work with ASP NET?

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.

How upload AJAX file to MVC?

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.

Can we download file using AJAX?

We cannot download the file through Ajax, must use XMLHttpRequest.


1 Answers

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.

like image 130
Eric Avatar answered Oct 12 '22 23:10

Eric