Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a class attribute to Html.BeginForm() in MVC3/4 preserving the minimal overload

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?

like image 249
Ralph Lavelle Avatar asked Oct 17 '12 01:10

Ralph Lavelle


2 Answers

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.

like image 172
Ralph Lavelle Avatar answered Oct 13 '22 04:10

Ralph Lavelle


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.

like image 41
StanK Avatar answered Oct 13 '22 03:10

StanK