如果我使用AJAX,文件上载过程中的HttpPostedFile为NULL

SVI*_*SVI 2 ajax asp.net-mvc file-upload

我在我的asp.net MVC项目中使用文件上传功能.在我开始在我的页面上使用一些AJAX功能之前,它工作得很好.

Ajax页面上的HttpPostedFile始终为NULL.

如何解决这个问题以及在我的页面上调用ajax?

Dar*_*rov 5

因为您无法使用AJAX上传文件,我建议您使用优秀的jquery表单插件,它允许您对表单进行ajaxify并支持文件上载.在幕后,该插件会生成一个隐藏的iframe来处理上传,并且对您完全透明:

<form id="myForm" action="/home/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" value="upload" />
</form>
Run Code Online (Sandbox Code Playgroud)

控制器:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    // TODO: handle the file here
    return PartialView("success");
}
Run Code Online (Sandbox Code Playgroud)

最后ajaxify形式:

$(function() {
    $('#myForm').ajaxForm(function(result) {
        alert('thank you for uploading');
    });
});
Run Code Online (Sandbox Code Playgroud)

另请注意HttpPostedFileBase代替HttpPostedFile控制器操作的用法.作为一个抽象类,这将简化您的单元测试.