[英]File Upload with Partial View MVC 5
我正在尝试通过我的MVC 5应用程序中的Html-Helper表单上传数字和文件。 提交模型后,似乎我的视图模型中的model.File
属性始终返回null
。
在添加model.File != null
检查之前,我的应用程序抛出了NullReferenceException
。
我的表单逻辑包含在名为UploadFile.cshtml
的部分视图中,因为我的表单逻辑需要与index.cshtml
不同的模型。
如何在我的[HttpPost]
控制器操作中从我的表单中读取File
属性?
index.cshtml
@Html.Action("UploadFile", "Home")
UploadFile.cshtml
@model FileViewModel
@using (Html.BeginForm("FormUpload", "Home", FormMethod.Post))
{
<div class="form-group">
@Html.TextBoxFor(m => m.Marker)
</div>
<div class="form-group">
@Html.TextBoxFor(m => m.File, new { type = "file" })
</div>
<input type="submit" name="submit" value="Submit" />
}
HomeController的
public PartialViewResult UploadFile()
{
return PartialView("UploadFile", new FileViewModel());
}
// /Home/FormUpload
[HttpPost]
public ActionResult FormUpload(FileViewModel model)
{
if (ModelState.IsValid)
{
if (model.File != null && model.File.ContentLength > 0 && model.File.ContentType == "application/pdf")
{
// Convert file to byte[] and upload
// ...
ViewBag.Message = "File Uploaded Successfully";
}
else
{
ViewBag.Message = "File Not Uploaded";
}
}
return RedirectToAction("Index");
}
FileViewModel
public class FileViewModel
{
public int ID { get; set; }
public int Marker { get; set; }
public string Filename { get; set; }
public HttpPostedFileBase File { get; set; }
}
您缺少表单的enctype属性,您需要为文件大小写指定:
@using (Html.BeginForm("FormUpload", "Home",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
有关详细信息,请参阅此文章 。
Html.BeginForm("FormUpload", "Home", FormMethod.Post))
应该
@using (Html.BeginForm("FormUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.