我正在构建一个ASP.NET MVC 3应用程序,并尝试使用jQuery Dialog上传照片。这是我的代码,但问题是我的model
的HttpPostedFileBase
对象(表示要上传的文件)在服务器端总是为空(HttpPost
方法)。
我的控制器
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>
$(function(){
$("#JqPostForm").submit(function(e){
e.preventDefault();
$.post("process_form.php", $("#JqPostForm").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});});
我建议您应该使用类似的东西来触发表单提交操作
我找到了这个问题和答案,我决定改变我的方法,使用HTML5来解决我的问题。谢谢,祝你好运。
使用HTML5,您可以使用Ajax和jQuery进行文件上传。不仅您可以进行文件验证(名称、大小和MIME类型)或使用HTML5进度标记(或div)处理进度事件。
据我所知,您无法使用$.post或Jquery的ajax上传文件。所以
$("#uploadProductPhotoForm").serialize()
不序列化文件输入。
您可以在提交功能中执行以下操作:
使用javascript:获取文件输入
var fileInput = document.getElementById("IdOfYourFileInput");
它将有一个包含所选文件的files
属性,然后您可以使用FormData
和XMLHttpRequest
上传它
var form = new FormData();
form.append("NameOfTheInput", fileInput.files[0]);
form.append("NameOftheId", id);//this is your productId
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Product/AddProductPhoto/", true):
xhr.send(form);