【发布时间】: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