BARJ
BARJ

Reputation: 2020

asp.net MVC input attribute of type file with bootstrap style casuing strange result

I want to have a file-input attribute with the same style as the upload button as seen in the image below. The upload button is using bootstrap. When I apply bootstrap to button A with "TextBoxFor", I get this weird looking button. When I apply bootstrap to button B with "LabelFor", I get the desired style, only without the functionality of the file-input attribute.

My question is, how do I get a file-input field with a certain bootstrap style applied and maintain its functionality. With the same result(style) as if it was applied to a submit-type attribute. I prefer to use one of the html helpers, because I am trying to understand them.

Button A vs Button B

A:

@Html.TextBoxFor(m => m.File, new { type = "file", @class = "btn btn-default btn-file" })

B:

@Html.LabelFor(m => m.File, new { type = "file", @class = "btn btn-default btn-file" })

Upload button:

<input type="submit" class="btn btn-default" value="Upload" />

Upvotes: 1

Views: 15602

Answers (2)

Synctrex
Synctrex

Reputation: 881

This is a year old, but I just spent a while struggling with this and figured I'd share my solution. I'd be interested to hear how you resolved this!

I wrapped the razor stuff with a div that uses the form-control class, like so:

...
<div class="col-md-8">
     <div class="form-control">
          @Html.TextBoxFor(model => model.Filepath, new { type = "file", id = "filepath", accept = ".jpg, .jpeg, .gif, .png" })
          @Html.ValidationMessageFor(model => model.Filepath, "", new { @class = "text-danger", style = "font-weight: bold;" })
          <p class="help-block">
               Images must be 300x300 pixels or smaller, and in a .PNG, .JPG, or .GIF format.
          </p>
      </div>
</div>
...

However, since Bootstrap's form-control class puts a border around things by default, I had to override those.

border: none;
box-shadow: unset;

The result was pretty clean.

finished product

Upvotes: 1

Germano Plebani
Germano Plebani

Reputation: 3655

This is the normal aspect of an html input type file (A), and the aspect change from browser to browser. If you want to change as it appears, you have to work with some CSS hiding the real input with another fake over or something similar.

Here is a good example to do this with bootstrap 3.

Upvotes: 5

Related Questions