Reputation: 3991
So, here's a challenging one that has been troubling me.
I have a "complex" model structure:
ExpenseReport
Expense*
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:
Everything else is binding correctly, each nested list item contains the right prefixes, etc;
FileData is the name of the byte[] property in my ExpenseFile model;
Upvotes: 1
Views: 674
Reputation: 3991
Just figured it out. Here's the answer, in case somebody stumbles upon the same problem:
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