How to do a ASP.NET MVC Ajax form post with multipart/form-data?

5
(5)

Suppose your Ajax form like this:

@using (Ajax.BeginForm("UploadFile", null, new AjaxOptions { HttpMethod="POST", UpdateTargetId = "result" }, new { enctype = "multipart/form-data" }))
{         
  <label id="lblUploadNewFile" for="fileUploadControl">Upload New File</label>     
  <input type="file" name="fileToUpload" id="fileUploadControl"/>
  <input id="btnFileUpload" type="submit" value="Upload" />
  <span id="result" />            
}

If you want to post a file using ASP.NET MVC Ajax form?, you need to add the following line of coding in the same page of your Ajax form.

window.addEventListener("submit", function (e) {
    var form = e.target;
    if (form.getAttribute("enctype") === "multipart/form-data") {
        if (form.dataset.ajax) {
            e.preventDefault();
            e.stopImmediatePropagation();
            var xhr = new XMLHttpRequest();
            xhr.open(form.method, form.action);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (form.dataset.ajaxUpdate) {
                        var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        if (updateTarget) {
                            updateTarget.innerHTML = xhr.responseText;
                        } 
                    }
                }
            };
            xhr.send(new FormData(form));
        }
    }
}, true);

 

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?