I\'m trying to upload a file using Ajax.BeginForm(), but it\'s not working out.
My view contains:
@using (Ajax.BeginForm(\"UploadFile\", null, new Aj
You cannot upload files using AJAX. This is not supported. If you want to do that you could either use some file upload plugin such as Uploadify or Blueimp File Upload or use the HTML 5 File API if the client browser supports it.
You can do this without additional libraries.
I came across this little hack, which resolves it nicely
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);
Found http://www.acnenomor.com/1762557p1/c-mvc3-ajaxbeginform-to-upload-file-not-working
You can do this to get this work: get jquery.form library from nuget and import it to your cshtml file.You should create your form with @Html.BeginForm. then bottom of your form write this script to ajax-ify your form:
$(function(){
$('#formId').ajaxForm({
complete:function(xhr){...},
success:function(){...},
error: function(){...}
});
});
With these steps you can pass a file to controller.
very simple solution:
@using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "startLoader",
OnSuccess = "Update_Record",
UpdateTargetId = "Succ_Msg"
},new { enctype = "multipart/form-data" }))
notice the new { enctype = "multipart/form-data" }
which tells the razor page to add the enctype
that can pass HttpPostedFileBase
good luck:).