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().
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.
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.
This is really just the default template with the classes changed to the ones used by Bootstrap:
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.