我正在構建一個ASP.NET MVC 3應用程序,並且我正嘗試使用jQuery對話框上傳照片。這裏是我的代碼,但問題是我的model
(巫婆代表要上傳的文件)的HttpPostedFileBase
對象在服務器端始終爲空(方法HttpPost
)。使用jQuery對話框在ASP.NET MVC站點上傳照片
我控制器
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 });
}
模型
public class UploadImageModel
{
public int ProductId { get; set; }
[FileExtensions(Extensions = "jpg, jpeg, png")]
public HttpPostedFileBase File { get; set; }
}
上傳局部視圖(_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>
}
主視圖
<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>
我不需要提交表單按鈕,我在'上傳'按鈕中處理它(請參閱對話框的定義)。另外,通過調試,我點擊了HttpPost方法... – SidAhmed