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.
//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();
}
}
//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();
}
}