Agares Agares - 4 months ago 28
HTML Question

Integrating Twitter Bootstrap with MVC 3 forms

I am using MVC 3 and Twitter Bootstrap. What I want is to integrate both of them. The big problem for me is forms. I am using the

and it is a problem, when it comes to the validation, I want it to generate HTML like this:

<div class="control-group error">
<label for="field" class="control-label">OMG this label is so awesome: </label>
<div class="controls">
<input type="text" name="field" id="field" value="yeah" />
<span class="help-inline">Eventually some error :C</span>

Here is my HtmlHelper code:

@Html.LabelFor(x => x.Field)
@Html.EditorFor(x => x.Field)
@Html.ValidationMessagesFor(x => x.Field)

The problem is that I want the class error on outermost div to be set only if there actually is an error on this field. Other problem is that I don't know how to enforce using span tag for errors. I could write my method in HtmlHelper, but it'd make me reimplement almost all of the functionality of the
. Is there a simpler way to do this? And what about the unobtrusive validation?


I encountered the same challenge and with some help for the labels (see below), here is what I got :

<div class="control-group @if (!ViewData.ModelState.IsValidField("Name")) { @Html.Raw("error"); }">
    @Html.LabelFor(model => model.Name, new {@class = "control-label"})
    <div class="controls">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name, null, new {@class = "help-inline"})

Html.LabelFor implementation :

I didn't try with the unobstrusive validation, but it seems you just have to activate it.

If you are looking for a global error, you should use something like :

@if (ViewData.ModelState.IsValid == false) {
    <div class="alert alert-error"><button class="close" dismiss="alert">x</button><!-- some text--></div>

There is a live example (in french) here :

The whole project source code should be available some time soon (see my profile - or ask me directly).