microtuts

ASP.NET MVC 2/3: File Upload Model Binding (HttpPostedFileBase)

Whenever I create a form with a file upload field and try to get the file information to bind to my view model I run into a snag. It’s really easy to do though; here are the steps:

Your view model should look something like this:

HttpPostedFileBase will be the property that holds our file upload information. This should bind automatically but we need to make sure our form is set up right. It’s important that our form as an enctype of multipart/form-data.

 

Using Razor it would look like this:

 

I had some trouble using Razor to generate the actual file upload control so I just use plain HTML like this:

 

In the controller we should now have the file upload information binded to the posted model. Using this information should look something like this:

 

And there you have it. I hope that works out for you.


Creating your first programming language is easier than you think.

Understanding how a programming language works is a surefire way to be a better developer. Read more.


Suggested Reading


written by Ryan Bosinger
Ryan is a web developer living and working in Banff Alberta. He also writes for giftsforpeoplewitheverything.com and freefoley.com.

5 Responses to “ASP.NET MVC 2/3: File Upload Model Binding (HttpPostedFileBase)”

  1. pramod says:

    I want to do this by @using (Ajax.BeginForm for partial refresh on upload. how can i do.

  2. Noman says:

    i appreciate you work but write down or send complete code when i pass same info using model class object mean CollectionViewModel objet but it will not work

  3. Eric Bartolo says:

    Hi Ryan,

    Big thank you as after hours of searching and trial and error I managed to upload files on MVC thanks to this post! I was missing the enctype which none of the other mentioned!

    Thank you so much, if only I found this article before…

  4. Manoj Kalla says:

    Very good. . .article. . thanks brother.

Leave a Reply