Is there any way to get posted files (<input type="file" />
) to take part in model binding in ASP.NET MVC without manually looking at the request context in a custom model binder, and without creating a separate action method which only takes a posted file as input?
I would have thought that this would work:
class MyModel {
public HttpPostedFileBase MyFile { get; set; }
public int? OtherProperty { get; set; }
}
<form enctype="multipart/form-data">
<input type="file" name="MyFile" />
<input type="text" name="OtherProperty" />
</form>
public ActionResult Create(MyModel myModel) { ... }
But given the above scenario, MyFile
isn't even part of the value provider values in the binding context. (OtherProperty
is, of course.) But it works if I do this:
public ActionResult Create(HttpPostedFileBase postedFile, ...) { ... }
So, why does no binding occur when the parameter is a model, and how can I make it work? I have no problem with using a custom model binder, but how can I do this in a custom model binder without looking at Request.Files["MyFile"]
?
For consistency, clarity and testability, I'd like my code to provide automatic binding of all properties on a model, including those bound to posted files, without manually inspecting the request context. I am currently testing model binding using the approach Scott Hanselman wrote about.
Or am I going about this in the wrong way? How would you solve this? Or is this not possible by design due to the history of separation between Request.Form and Request.Files?
enctype
attribute on the form. It must be specified as"multipart/form-data"
. Otherwise, theHttpPostedFileBase
argument with matching name as thename
attribute on the input tag, will remainnull
on POST. – Hackle