I'm building an ASP.NET MVC 3 application, and I'm trying to use a jQuery Dialog to upload a photo. Here is my code, but the problem is that the HttpPostedFileBase
object of my model
(witch represent the file to upload) is always null on the server side (HttpPost
method).
My controller
public ActionResult AddProductPhoto(int id)
{
var model = new UploadImageModel {ProductId = id};
return PartialView("_UploadFile", model);
}
[HttpPost]
public ActionResult AddProductPhoto(UploadImageModel model)
{
// model.File is always null
return Json(new { Success = true });
}
The model
public class UploadImageModel
{
public int ProductId { get; set; }
[FileExtensions(Extensions = "jpg, jpeg, png")]
public HttpPostedFileBase File { get; set; }
}
The upload partial view (_UploadFile)
@model DalilCompany.Models.UploadImageModel
@using (Html.BeginForm("AddProductPhoto", "Product", FormMethod.Post,
new { id = "uploadProductPhotoForm", enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
@Html.HiddenFor(m => m.ProductId)
<div>
@Html.LabelFor(m => m.File)
@Html.TextBoxFor(m => m.File, new { type = "file" })
</div>
}
main view
<span productId ="@Model.ProductId" id="add_product_photo_link">
Upload photo
</span>
<div id="AddPhotoDlg" title="" style="display: none"></div>
<script type="text/javascript">
$(function () {
$("#AddPhotoDlg").dialog({
autoOpen: false,
width: 550,
height: 250,
modal: true,
buttons: {
"Upload": function () {
$.post("/Product/AddProductPhoto",
$("#uploadProductPhotoForm").serialize(),
function () {
$("#AddPhotoDlg").dialog("close");
alert('upload success');
});
},
"Close": function () { $(this).dialog("close"); }
}
});
});
$("#add_product_photo_link").click(function () {
var id = $(this).attr("productId");
$("#AddPhotoDlg").html("")
.dialog("option", "title", "Ajouter une photo")
.load("/Product/AddProductPhoto/" + id,
function () { $("#AddPhotoDlg").dialog("open"); });
});
</script>