HttpPostedFileBase始终返回null ASP.NET MVC 5

时间:2016-01-04 19:40:38

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

当我尝试在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>

}

这里有人可以发现问题吗?

2 个答案:

答案 0 :(得分:0)

控制器中的

 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" />
}

使用input元素的name属性可以将文件从视图中检索到控制器

答案 1 :(得分:0)

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