使用部分视图 MVC 5 上传文件

本文关键字:文件 MVC 用部 视图 | 更新日期: 2023-09-27 18:30:55

我正在尝试通过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; }
}

使用部分视图 MVC 5 上传文件

您缺少表单的 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"}))