ASP.NET MVC – How to handle one or more uploaded files as ViewModel properties using HttpPostedFileBase class

ASP.NET MVC - Aggiungere uno o più percorsi di ricerca predefiniti per le View

Dealing with file uploads in ASP.NET / ASP.NET Core MVC can be tricky, expecially if we want to stick to the ViewModel pattern and handle them just like standard properties in our POCO classes.

If it weren’t the case, we could easily work around it and do something like this in the View:

And then retrieve the file in the Controller in the following way:

To put it short, the file is kept outside the model and treated in a separate way.

This is a common and practical way to handle file uploads: I stumble upon this a number of times, from friends code to some GitHub project. Although being perfectly fine, it’s definitely not the proper way to deal with such scenario: what if we are supposed to receive multiple files? Wouldn’t be much better to have them inside the ViewModel instead?

Luckily enough, the MVC framework allows us to deal with it in a much better and cleaner way. Here’s how:

In the ViewModel:
In The View:
In the Controller:
That’s it!

In case we need to support multiple files, we are free to choose between the following:

  • create multiple properties and implement them separately just like the one above;
  • change the   property to something like public   and then span multiple   controls.

As always, the choice is ours.

 

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

5 Comments on “ASP.NET MVC – How to handle one or more uploaded files as ViewModel properties using HttpPostedFileBase class”

  1. Thanks so much, I have tried this in Ajax.BeginForm but it doesn’t work, the same code in Html.BiginForm works well, does ajax not allow to upload file or should I adjust my code somewhere? And sorry for my bad English if anything not clear just tell me, thx!

    1. Hello there,
      I’m happy you did like our post: if you found it useful, don’t forget to add a like on our Facebook page :)

      Regarding your query, I personally do not like Ajax.BeginForm for a number of reasons: whenever I need to post a form using AJAX, I always end up using a JQuery form plugin or other JS-based tools that allow me to manually setup and fine-tune the ajax request/response cycle.

      Here’s a good example from StackOverflow, including full source code:

      https://stackoverflow.com/a/19044689/1233379

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.