Developer’s How To: Styling a File Upload in Microsoft MVC 4

Implementing a file upload in an MVC Web Application seems to be pretty easy to do. Styling an upload in MVC 4, however, seems to be a bigger issue, but here I am going to give an example of how it can be done. The basic rule is that if you have an MVC 4 Web Application you most probably already have all the .css style sheets in place, and all you need is to get them applied to the file upload HTML element. Note: the code shown in the example is available for download.

Let’s start with a non-styled implementation:

Model Style File Upload MVC 4

A straightforward approach using the native MVC HTML helper for file input:

View Style File Upload MVC 4


Controller Style File Upload MVC 4

But here is the problem: this is how the input of type file will look like:

File input in Microsoft MVC 4

This is not something any of us would like to see in our web application.  It turns out that the file input, proves extremely difficult to style. The few working tricks I was able to find online included a lot of HTML manipulations, and all of them went down the path of hiding the file input element and replacing it with different, easily styled elements. But I kept searching for a concise and easy-to-read solution, and after a bit of playing with the code, I came up with the following.


To allow custom styling, we are going to hide the file input and replace it with easily styled HTML elements, and then use a few lines of jQuery to ensure that the required functionality is still in place. Note that I am not adding any particular styling to these elements, because my Web Application already has a common style sheet, and my goal is simply making the upload page look like the rest of the website. If this is not the case, any custom inline/css styles could easily be added to the displayed elements.

Updated View

updated view Style File Upload MVC 4

And the code in the Model & Controller doesn’t change.

Now let’s add two jQuery functions. The first one will make sure that when we click the “Browse” button the file input click event will fire. The second will let us display the name of the chosen file to the user.

Script Style File Upload MVC 4

Keep in mind that the following HTML helper

@Html.TextBoxFor(m => m.File, new { type = "file", style = "display:none" })

Will generate this HTML snippet

<input data-val="true" data-val-required="File is required." id="File" name="File" style="display:none" type="file" value="">

So your $(“#File”) selector in jQuery code has to match the name of the File property in your Model.

That’s it; now you are good to go. Happy styling!

By |2018-04-18T22:27:08+00:00November 13th, 2012|