Reputation: 5769
I'm in the process of upgrading my app to Bootstrap 2.1.1 and I need to add a class attribute (class="form-horizontal") to many of the form tags. The problem is, most of the forms use the rather beautiful
@using (Html.BeginForm()) {
format which I'd rather keep. The obvious way to get the class attribute in there is to use the following overload, for example:
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal" })) {
But I'd rather not do that. What is the best way to add a class attribute to my form?
I've thought about using a jQuery document ready handler to .addClass("form-horizontal") to forms, but am worried that users would see the dreaded 'flash of unstyled content'.
Another approach might be to use a less-style mix-in, to add the .form-horizontal class to all form style rules but I haven't used less yet, so I'm not sure about this one.
Anyone know the best way to solve this problem?
Upvotes: 13
Views: 10751
Reputation: 5769
Following StanK's advice, and the advice of some other answers on SO, I created an extension method specifically tailored to that Bootstrap form layout:
public static MvcForm BeginHorizontalForm(this HtmlHelper helper) {
return helper.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal" });
}
which allows me to use
@using (Html.BeginHorizontalForm()) {...
which is nice and elegant.
Upvotes: 21
Reputation: 4770
What about writing a custom helper method which calls the overload required, passing in 'form-horizontal'?
Then, you views would use @using (Html.BootstrapBeginForm()) {
, leaving you views nice and tidy.
Upvotes: 15