Reputation: 8474
In the case that the user doesn't have Javascript activated, in order to draw a form, I begin this way:
<% using (Html.BeginForm("Create", "Language", FormMethod.Post,
new {enctype="multipart/form-data"}))
{ %>
If the user has Javascript activated, the following code is used:
<% using (Ajax.BeginForm("Create", "Language",
new AjaxOptions { UpdateTargetId = "CommonArea" },
new { enctype = "multipart/form-data" }))
{ %>
The problem is this:
In the first case, I can get the file uploaded using the following instruction in the business layer:
// Get the uploaded file
HttpPostedFile Flag = HttpContext.Current.Request.Files["Flag"];
In the second case, this instruction doesn't work. How do I know upload that file using the Ajax.BeginForm? Is the code right? Can anyone more experience advise about using jQuery plug-in to upload file before the form submission?
Thank you
Upvotes: 1
Views: 5242
Reputation: 532515
You can't do a file upload using AJAX alone. Many (most?) asynchronous uploaders use a dynamically created, hidden iframe containing a form that posts back to the server normally. I'd suggest looking through the jQuery plugin repository for "ajax upload" and seeing if you can find a plugin that will work for you that will do the upload using a combination of javascript and an iframe.
NOTE: At this time Firefox and Chrome support the XMLHttpRequest2 which does allow uploading via an AJAX request. One would expect that support for this will become universal at some point and true asynchronous upload will be possible in all browsers. Browsers that support FormData can also upload files using that interface.
Upvotes: 3
Reputation: 685
jQuery Form plugin has a very very neat and completely transparent way of doing this. It automatically transforms the into the hidden iframe. Only what you have to do is to call .ajaxForm() on your form to initialize the component. Only problem is that if you return json from the action method, you have to change the content type, so your callback function recognize it as a json.
It's a bit weird, but this is working for me:
JsonResult result = Json(response);
result.ContentType = "text/html";
return result;
Upvotes: 1