Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I'm trying to upload a file using Ajax.BeginForm() but it's not working out.

My View Contains:
C#
@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" />            
}

and the corresponding Controller is:
C#
[HttpPost]
public string UploadFile(FormCollection formData)
{
  HttpPostedFileBase file=null;
  try
  {
   file = Request.Files[0];
  }
  catch { }

  if ( file!=null && file.ContentLength > 0)
    {
     file.SaveAs(string.Concat(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(file.FileName)));
     return "Successfully Uploaded";
    }
  else
    {
      return "Upload Failed, please try again.";
    }

  }



now, the problem is- It's uploading the file but not doing asynchronous when I remove "jquery.unobtrusive-ajax.js". It does a full postback. When I add "jquery.unobtrusive-ajax.js" it in my view, It's doing asynchronous but not sending upload file in form data. No file is being sent to the server in Request.Files[].

Somebody please help.

Thanks a lot in advance!
-Sunny.
Posted
Updated 2-Dec-19 0:01am
v2

I came across this little hack, which resolves the problem of no files for Ajax.BeginForm submissions:

JavaScript
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
 
Share this answer
 
Comments
Jijutj 16-Jun-15 6:32am    
Is there a way to check the file type and give error using this code?
Use HttpPostedFileBase instead of FormCollaction.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900