Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 AjaxOptions { HttpMethod="POST",     UpdateTargetId = "result" }, new { enctype = "multipart/form-data" }))
{
   <label id="lblUploadNewFile" for="fileUploadControl">Upload New File&lt;/label>
   <input type="file" name="fileToUpload" id="fileUploadControl"/>
   <input id="btnFileUpload" type="submit" value="Upload" />
   <span id="result" />
}

and the corresponding Controller is:

[HttpPost]
public string UploadFile(FormCollection formData)
{
   HttpPostedFileBase file=null;

   try
   {
      file = Request.Files[0];
   }
   catch { }

   if ( file!=null &amp;&amp; file.ContentLength &gt; 0)
   {
      file.SaveAs(string.Concat(
            AppDomain.CurrentDomain.BaseDirectory,
            Path.GetFileName(file.FileName)));

      return &quot;Successfully Uploaded&quot;;
   }
   else
   {
      return &quot;Upload Failed, please try again.&quot;;
   }
}

The problem is that it's uploading the file, but no longer doing any asynchronous posts when I remove jquery.unobtrusive-ajax.js. Instead, it does a full post-back.

When I add jquery.unobtrusive-ajax.js in my view, it's doing it asynchronously, but it is not sending an upload file in the form data. No file is being sent to the server in Request.Files[].

like image 684
Sunny Sharma Avatar asked Jun 11 '13 06:06

Sunny Sharma


People also ask

What is the difference between Ajax BeginForm and HTML BeginForm?

BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

What is use of Ajax BeginForm?

Ajax. BeginForm is the extension method of the ASP.NET MVC Ajax helper class, which is used to submit form data to the server without whole page postback.

What is the purpose of UpdatetargetId when specifying an Ajax form?

UpdatetargetId is the id of the DOM element which you want to update depending upon repsonse from the server. If you are returning any View or PartialView from controller using Ajax. BeginForm . This DOM element will be updated and will have view content you have returned.


1 Answers

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.

like image 103
Darin Dimitrov Avatar answered Sep 19 '22 14:09

Darin Dimitrov