MVC UPLOAD FILE WITH MODEL - SECOND PARAMETER POSTED FILE IS NULL

Pravesh Singh

Total Post:101

Points:709
Posted by  Pravesh Singh
C#  Mvc4  Model 
 1658  View(s)
Ratings:
Rate this:

I have a simple model with 1 string property which I render on a simple view.

 

the view looks like the following:

 

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { encType="multipart/form-data" }))

{

    @Html.TextBoxFor(m => m.FirstName)

    <br /><br />

 

    <input type="file" name="fileUpload" /><br /><br />

    <input type="submit" value="submit me" name="submitme" id="submitme" />

}

Controller is this:

 

[HttpPost]

public ActionResult UploadFile(UploadFileModel model, HttpPostedFileBase file)

{

   // DO Stuff

   return View(model);

}

Now, when I submit, the model DOES get populated but the second parameter being HttpPostedFileBase is null. However when doing Request.Files - it does seem to show there is a file in the Request being posted. How can I actually get the second parameter to bind?

  1. jayprakash sharma

    Post:117

    Points:821
    Re: mvc upload file with model - second parameter posted file is null

    Why not add the uploaded files to your model like this:

     

    public class UploadFileModel

    {

        public UploadFileModel()

        {

            Files = new List<HttpPostedFileBase>();

        }

     

        public List<HttpPostedFileBase> Files { get; set; }

        public string FirstName { get; set; }

        // Rest of model details

    }

    Then change your view to this:

     

    @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { encType="multipart/form-data" }))

    {

        @Html.TextBoxFor(m => m.FirstName)

        <br /><br />

     

        @Html.TextBoxFor(m => m.Files.Files, new { type = "file", name = "Files" })<br /><br />

        <input type="submit" value="submit me" name="submitme" id="submitme" />

    }

    Then your files will be posted back as follows:

     

    public ActionResult UploadFile(UploadFileModel model)

    {

        var file = model.Files[0];

        return View(model);

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!