问题原因是在使用jQuery Mobile构建Razor表单时,MVC不会将从表单中选择的文件正确绑定到控制器中的HttpPostedFileBase属性。为了解决这个问题,需要在Controller中手动绑定HttpPostedFileBase。
以下是解决方法的代码示例:
在View中,使用类似以下的表单:
@using(Html.BeginForm("ActionName","ControllerName",FormMethod.Post, new { enctype = "multipart/form-data"})) { }
然后在Controller的相应Action中使用以下代码将文件绑定到HttpPostedFileBase属性:
[HttpPost] public ActionResult ActionName(FormCollection formCollection) { HttpPostedFileBase fileBase = Request.Files.Count > 0 ? Request.Files[0] : null;
if (fileBase != null && fileBase.ContentLength > 0)
{
//process file here
return View("UploadSuccessful");
}
else
{
ModelState.AddModelError("", "Please select a file.");
return View("UploadFailed");
}
}
这个解决方法将确保你可以从表单中正确地绑定文件到HttpPostedFileBase。