Using Bootstrap with MVC Views

I’m a lazy developer by nature. That means I don’t like to do extra work when it isn’t necessary. Therefore, I am a big fan of MVC’s HTML helpers. One of my favorites is Html.EditorForModel().

In case you haven’t heard about it, Bootstrap is a newish set of CSS and JavaScript from Twitter that makes designing responsive web sites pretty easy. The CSS has a modern and clean look, and pages based on it scale very well, even on mobile devices.

The problem I ran into is that Bootstrap expects form elements (labels, inputs, etc.) to have specific classes so that it knows how to display them properly. But the EditorForModel helper doesn’t know about Bootstrap. Thus, I needed to find a way to substitute the default classes for Bootstrap’s.

The first thing I tried was to use jQuery to change the classes dynamically.

image

It worked, but I didn’t like having to rely on JavaScript for this. Short of rewriting all of the editing views and abandoning Html.EditorForModel, I thought that there must be a way to customize how the helper generates its HTML.

I found the solution at an older blog post by Brad Wilson. He describes how to override the default template used by EditorForModel to generate a table layout for the form fields.
Once I got that code, it was a simple matter of changing the HTML to include the form classes used by Bootstrap. The example uses ASP.NET syntax. I’m using Razor, so I had to make some minor modifications. The complete class is shown here.
Views/Shared/EditorTemplates/Object.cshtml

image

This is really just the default template with the classes changed to the ones used by Bootstrap:

  • control-group
  • control-label
  • controls
  • help-inline

There are obviously a lot more things that could be added to this, but this should be enough to get you started.

As is typical for me, I spent a lot of time working so that I could be lazy. In the end, however, I’m happy with this solution. I didn’t have to make any changes to my Views, and it keeps my code nice and DRY.

Comments

Popular posts from this blog

How to copy your Frozen Free Fall progress to a new phone

Ionic vs. Bootstrap - for a Web App

How I Finally Got AdMob and Ionic Framework to Play Nice Together