【问题标题】:File Upload with Partial View MVC 5使用局部视图 MVC 5 上传文件
【发布时间】: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


    【解决方案1】:

    您缺少表单的 enctype 属性,您需要为文件大小写指定该属性:

    @using (Html.BeginForm("FormUpload", "Home", 
                           FormMethod.Post, 
                           new { enctype = "multipart/form-data" }))
    

    更多详情请参阅this article

    【讨论】:

    • 哦,哇,错过了这么简单的事情。感谢您及时的回复!当 SO 允许时,我会将其标记为答案。
    • 是的,初学者大多会错过这一点,他们无法弄清楚为什么文件为空:)
    【解决方案2】:
    Html.BeginForm("FormUpload", "Home", FormMethod.Post))
    

    应该是

    @using (Html.BeginForm("FormUpload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) 
    

    【讨论】:

      猜你喜欢
      • 2015-09-20
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多