【问题标题】:HttpPostedFileBase always return null ASP.NET MVC 5HttpPostedFileBase 总是返回 null ASP.NET MVC 5
【发布时间】:2016-04-08 12:07:17
【问题描述】:

当我尝试在 ASP.NET MVC5 中上传文件时遇到问题。

不知何故“HttpPostedFileBase 文件”总是返回 null,我找不到我的问题。

我的代码: (控制器)

 public ActionResult Edit(PMNieuwePloeg ploeg, FormCollection frm, HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("/Content/ImagesPloegen/"), fileName);
            file.SaveAs(path);

            ploeg.NieuwPloeg.ImageUrl = file.FileName;
        }
        else
        {
            ploeg.NieuwPloeg.ImageUrl = "/geen.jpg";
        }

        if(ploeg.NieuwPloeg.LandID > 0)
        {
            ploeg.NieuwPloeg.UserId = UserManager.FindByName(User.Identity.Name).Id;
            ploeg.NieuwPloeg.UserName = UserManager.FindByName(User.Identity.Name).UserName;
            repoPloegen.Edit(ploeg.NieuwPloeg);

        }
        return RedirectToAction("Index");

    }

查看

@using (Html.BeginForm("Edit","Ploegen", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Ploeg</h4>


    <div class="form-group">
        @Html.LabelFor(model => model.NieuwPloeg.ImageUrl, "Ploeg Image", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="file" required />

        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>

}

这里的任何人都可以发现问题吗?

【问题讨论】:

  • 您可以尝试将输入名称更改为 file1 和操作参数吗?
  • var UploadedFile = Request.Files["file"];
  • 如果您有两个同名操作,请在操作顶部使用 [HttpPost]。

标签: c# asp.net asp.net-mvc httppostedfilebase


【解决方案1】:

在控制器中

 HttpPostedFileBase casteCertificate = Request.Files["UploadRegCard"];

在视图中

@using (Html.BeginForm("ActionMethod", "Controller", FormMethod.Post, new { enctype = "multipart/form-data", name = "myForm", id = "myForm" }))
    {
     <input type="file" name="UploadRegCard" id="UploadRegCard" class="form-control" />
}

使用输入元素的名称属性,您可以将文件从视图检索到控制器

【讨论】:

    【解决方案2】:

    检查控制器中的Request.Files 数组。它应该包含您从客户端发布的所有文件

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 2019-09-17
      • 2014-06-29
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2019-05-03
      相关资源
      最近更新 更多