Is there any way to get posted files () to take part in model binding in ASP.NET MVC without manually looking at the reques
It turns out the reason is that ValueProviderDictionary
only looks in Request.Form
, RouteData
and Request.QueryString
to populate the value provider dictionary in the model binding context. So there's no way for a custom model binder to allow posted files to participate in model binding without inspecting the files collection in the request context directly. This is the closest way I've found to accomplish the same thing:
public ActionResult Create(MyModel myModel, HttpPostedFileBase myModelFile) { }
As long as myModelFile
is actually the name of the file
input form field, there's no need for any custom stuff.
Another way is to add a hidden field with the same name as the input:
<input type="hidden" name="MyFile" id="MyFileSubmitPlaceHolder" />
The DefaultModelBinder will then see a field and create the correct binder.
You don't need to register a custom binder, HttpPostedFileBase
is registered by default in the framework:
public ActionResult Create(HttpPostedFileBase myFile)
{
...
}
It helps to read a book every once in awhile, instead of relying solely on blogs and web forums.
Have you looked at this post which he links to from the one you linked to (via another one...)?
If not, it looks quite simple. This is the model binder he uses:
public class HttpPostedFileBaseModelBinder : IModelBinder {
public ModelBinderResult BindModel(ModelBindingContext bindingContext) {
HttpPostedFileBase theFile =
bindingContext.HttpContext.Request.Files[bindingContext.ModelName];
return new ModelBinderResult(theFile);
}
}
He registers it in Global.asax.cs
as follows:
ModelBinders.Binders[typeof(HttpPostedFileBase)] =
new HttpPostedFileBaseModelBinder();
and posts with a form that looks like this:
<form action="/File/UploadAFile" enctype="multipart/form-data" method="post">
Choose file: <input type="file" name="theFile" />
<input type="submit" />
</form>
All the code is copied straight off the blog post...