user1987392
user1987392

Reputation: 3991

Uploading Multiple Files in a Complex Model on MVC4

So, here's a challenging one that has been troubling me.

I have a "complex" model structure:

ExpenseReport

An ExpenseReport contains a list of Expenses which may (or may not) contain a list of ExpenseFile objects.

The ExpenseFile object contains (among other attributes) a byte[] to store the file data.

I've already managed to create the whole view for this, that consists of a tabular structure in which a user can add/remove Expenses to the report, and on each individual Expense row, the user can add/remove ExpenseFile's. All that is done using jquery/ajax. The ExpenseFile EditorTemplate contains a

<input type="file" name="FileData" id="FileData" />

so the user may select the correspondent file.

The model structure (i.e. the Report, Expense and ExpenseFile object hierarchy) binds correctly, with the only exception being the ExpenseFiles' file data, which is always null!

I know that the input files are accessible in the controller via

ControllerBlahBlah(... IEnumerable<HttpPostedFileBase> FileData)

or that I could implement a custom ModelBinder that would get the file data like this

var file = controllerContext.HttpContext.Request.Files["FileData"] 
...

but is there a way for the default model binder to bind each input file to the correspondent ExpenseFile?

I'm asking this because if there isn't, I will probably have to implement a custom binder and that would be a pain as I don't know how to figure out how to bind each

controllerContext.HttpContext.Request.Files["FileData"] 

to the right file.

Any help/ideias are appreciated.

Notes:

Upvotes: 1

Views: 674

Answers (1)

user1987392
user1987392

Reputation: 3991

Just figured it out. Here's the answer, in case somebody stumbles upon the same problem:

  • I added a HttpPostedFileBase property on my ExpenseFile modelview;
  • I created my own EditFor for HttpPostedFileBase;
  • Then, on my ExpenseFile view, I use

    @Html.EditorFor(model => model.postedFile)

instead of

<input type="file" name="FileData" id="FileData" />

Now the filedata binds correctly and all I have to do is convert the HttpPostedFileBase's data to a byte[] on the server side (Controller).

Upvotes: 1

Related Questions