I have a problem when i try to upload a file in ASP.NET MVC5.
Somehow "HttpPostedFileBase file" always returns null, i can't find my problem.
My Code: (Controller)
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");
}
View
@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>
}
Can anyone on here spot the problem?
in Controller
HttpPostedFileBase casteCertificate = Request.Files["UploadRegCard"];
in view
@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" />
}
using name attribute of input element you can retrive file from view to controller
Check Request.Files
array in controller. It should contain all your posted files from client
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.