Mr. T
Mr. T

Reputation: 65

List of uploaded files with ASP.MVC 5 is empty

I have a webform where I want to select a list of files, enter some additional informations and submit the whole bundle. The controller should than process the list of files according to the additionally entered datas. Therefore, I want to bundle all in one Model:

public class MyModel
{
    public string AdditionalInformations { get; set; }
    public int AdditionalInformationsId { get; set; }
    public IEnumerable<HttpPostedFile> Files { get; set; }
}

public class MyController: Controller
{
    [HttpPost]
    public ActionResult UploadFile(MyModel Model)
    {
        switch(Model.AdditionalInformationsId)
        {
            case 1:
                // do something with Model.Files
            case 2:
                // do something else with Model.Files
            ...
        }

        RedirectToAction("Index");
    }
}

My view looks like

@model MyProgram.Models.MyModel
@using MyProgram.Models

@using (Html.BeginForm("UploadFile", "MyController", FormMethod.Post,
                                                  new { enctype = "multipart/form-data" }))
{        
    <div class="row">
        <div class="col-sm-6">                
            <input type="file" name="Files" multiple />
        </div>
        <div class="col-sm-6"></div>
    </div>
    <div class="row">
        <div class="col-sm-3">                
            @Html.DropDownListFor(model => model.AdditionalInformationsId, 
                                             ((MyDropDownList)Session["DDLists"]).companies, 
                                             Model.AdditionalInformation, 
                                             new { @class = "form-control", id = "ReceivingCompany" })
        </div>
        <div class="col-sm-3">
            <br />
            <button class="btn btn-default" type="submit">Upload</button>
        </div>
        <div class="col-sm-6"></div>
    </div>
}

If I now use the submit-Button, the model is sent to the controller. E.g. AdditionalInformationsId has the value entered in the form. But IEnumerable Files is allways empty, except if I submit the form without choosing any files for upload, in that case the list contains a null-object. Also adding the attribute id="Files" to the multiple-file input-tag does not work.

I can't find the error. Is there maybe a setting I have to set in the web.config?

Upvotes: 1

Views: 1454

Answers (1)

Shyju
Shyju

Reputation: 218832

Change your property type to IEnumerable of HttpPostedFileBase

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

Now the posted files will be mapped to the Files property in your HttpPost action.

Upvotes: 3

Related Questions