How to upload a file in an mvc3 c# ajax form
Tech-Today

How to upload a file in an mvc3 c# ajax form


It's easy to upload file in a synchronous form, where you just post the file and read a HttpPostedFile variable in the server side: In plain html form, take note of the form enctype property:

//the view (index.cshtml)
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{


}

public class FileController : Controller
{
//it should show index.cshtml view
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFile file)
{
if (file != null && file.ContentLength > 0)
{ //now you have a non-empty file
//to save in a local directory
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
file.SaveAs(path);
}
return new EmptyResult();
}
}
That should work no problem but what if you have an ajax form, asynchronously you will not be able to upload a file together with the other form fields. So I've used a 3rd party javascript library to create a hidden iframe that will contain a file field.
http://code.google.com/p/ajax-file-upload-struts2/source/browse/trunk/src/main/resources/template/com/davidjc/javascript/ajaxfileupload.js?r=4 So here's my implementation on uploading a file on an ajax form, using the javascript library I've mentioned above:

//index.cshtml view
<script src="@Url.Content("~/Scripts/ajaxfileupload.js")" type="text/javascript"></script>
<script type="text/javascript">
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: "@Url.Action("UploadAttachment", "File")",
secureuri: false,
fileElementId: 'FileUpload',
dataType: 'json',
data: {
Name: $('#Name').val(), //you can declare the other form elements here
},
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
//alert(data.error);
} else {
//alert(data.msg);
}
}
},
error: function (data, status, e) {
//alert(e);
}
}
)

return false;
}
@using (Ajax.BeginForm("Upload", "File", new { }, new AjaxOptions { }, new { enctype = "multipart/form-data" }))
{
</script>
<table>
<tr>
<td class="label">
@Html.LabelFor(m => m.Name)
</td>
<td>
<div class="field_container">
@Html.TextBoxFor(m => m.Name)
</div>
</td>
</tr>
<tr>
<td class="label">
@Html.LabelFor(m => m.PathToAttachment)
</td>
<td>
<div class="field_container">
@Html.TextBoxFor(m => m.FileUpload, new { type = "file" })
</div>
</td>
</tr>
</table>

}

public class FileController : Controller
{
//it should show index.cshtml view
public ActionResult Index()
{
return View();
}

//do nothing on form submit
[HttpPost]
public ActionResult AddAttachment(AttachmentModel model)
{
return Json(new { success = true });
}
//this is where the file gets save in the server
public ActionResult UploadAttachment(String Name, HttpPostedFile FileUpload)
{
if (FileUpload.ContentLength > 0)
{
var r = new Random();
var uploadPath = Server.MapPath("~/Uploads");
var filename = FileName.Replace("_", "");
var savedFileName = Path.Combine(uploadPath, Path.GetFileName(filename));
//now you have your file
}
return new EmptyResult();
}
}




- How To Change Jquery's Dialog Button Label At Run Time
Recently I've used a 3rd party jquery library that pops up a jquery dialog with form content. However if has a default button Save and Cancel, which most of the time is ok, but sometimes you have need to localized or change the label depending on...

- Mvc3 Ajax Validation Doesn't Work On A Jquery Served Form
To make automatic validation using data annotation on a model on mvc3 c# we need: 1.) A model with data annotation (ex. required attribute). 2.) Form with jquery declaration (jquery1.7, validate, validate unobtrusive, and unobtrusive-ajax. All are available...

- Jquery Copy Form Values Into Another Form
Recently I have a requirement to have two form on a single page. Why? It's because I have a search form that query records from the database with the aid of ajax. Then another form to generate a report based from the filters specified in the first...

- Mvc3 Dynamic Search Paging Using Pagedlist
Basically there's a great tutorial from this site: Unboxed solutions. -I've copied the codes and add some comments. I'll just try to add my own comments. 1.) First you need to install PagedList.Mvc from Nuget. a.) Go to Tools->Library Package...

- How To Make Uploadify Work On Codeigniter
Recently, I have a requirement to implement a multiple file upload in one of my project. During upload I also need to pass a variable which will classify the category of the uploaded files. The category is a dropdown control. What we need: 1.) codeigniter...



Tech-Today








.