【发布时间】:2016-01-18 18:06:12
【问题描述】:
我正在尝试通过我的 MVC 5 应用程序中的 Html-Helper 表单上传一个数字和一个文件。提交模型后,我的视图模型中的model.File 属性似乎总是返回null。
在添加model.File != null 检查之前,我的应用程序抛出了NullReferenceException。
我的表单逻辑包含在名为UploadFile.cshtml 的局部视图中,因为我的表单逻辑需要与index.cshtml 不同的模型。
如何在[HttpPost] 控制器操作中从我的表单中读取File 属性?
index.cshtml
@Html.Action("UploadFile", "Home")
上传文件.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" />
}
家庭控制器
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");
}
文件视图模型
public class FileViewModel
{
public int ID { get; set; }
public int Marker { get; set; }
public string Filename { get; set; }
public HttpPostedFileBase File { get; set; }
}
【问题讨论】:
标签: c# asp.net-mvc razor asp.net-mvc-5