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);