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</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 && file.ContentLength > 0)
{
file.SaveAs(string.Concat(
AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(file.FileName)));
return "Successfully Uploaded";
}
else
{
return "Upload Failed, please try again.";
}
}
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[]
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With