Robki
Robki

Reputation: 3

HttpPostedFileBase always return null ASP.NET MVC 5

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?

Upvotes: 0

Views: 1314

Answers (2)

Andrew
Andrew

Reputation: 1534

Check Request.Files array in controller. It should contain all your posted files from client

Upvotes: 0

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

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

Upvotes: 1

Related Questions