Not able to upload file using Ajax.BeginForm() asynchronously

后端 未结 4 1678
故里飘歌
故里飘歌 2020-12-01 21:56

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         


        
相关标签:
4条回答
  • 2020-12-01 22:01

    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.

    0 讨论(0)
  • 2020-12-01 22:01

    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

    0 讨论(0)
  • 2020-12-01 22:04

    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.

    0 讨论(0)
  • 2020-12-01 22:07

    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:).

    0 讨论(0)
提交回复
热议问题