我已经在mvc3中正常提交了一个文件。现在我需要用Ajax做同样的事情。所以我使用了这个jquery插件:http://jquery.malsup.com/form/#ajaxSubmit
查看代码:
$(document).ready(function () {
var options = {
url: "/Home/TakeFile",
dataType: "json",
success: showResponse
};
$("#File").submit(function () {
alert("submit");
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseText, statusText, xhr, $form) {
alert("showResponse");
alert(responseText.fileName);
}
</script>
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" />
<input type="submit" value="Click to submit" id="button" />
}
Controller 代码:
[HttpPost]
public ActionResult TakeFile(HttpPostedFileBase file)
{
return Json(new { fileName=file.FileName});
}
我的“TakeFile”方法中的文件参数始终为 null。似乎无法使其工作。另外,我们可以使用“Ajax.BeginForm()”帮助程序来完成此操作吗?
最佳答案
<input>
的 name 属性<form>
内的 html 元素用于在表单提交后引用表单数据。
注意:只有具有 name 属性的表单元素才会在提交表单时传递其值。
作为操作方法public ActionResult TakeFile(HttpPostedFileBase file){..}
有一个参数名称'file',在 View 中,file 输入元素应该有一个 name='file'
属性。更新代码:
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" value="Click to submit" id="button" />
}
关于asp.net-mvc-3 - 通过 Ajax 在 ASP.NET MVC3 中上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10174116/