Integrating Twitter Bootstrap with Asp.net MVC 3 forms Integrating Twitter Bootstrap with Asp.net MVC 3 forms asp.net asp.net

Integrating Twitter Bootstrap with Asp.net MVC 3 forms


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"})    </div></div>

Html.LabelFor implementation : https://stackoverflow.com/a/6722082

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 : http://ws.sherbrow.fr/auth

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


A bit late answer, but I'll propose a better solution and you should totally accept my answer ;)

Use TwitterBootstrapMVC.

With a single line of code it will generate exactly the html you need:

@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Field)

For Global error all you need to write is:

@Html.Bootstrap().ValidationSummary()

... it will generate an alert div with all errors listed in it.Notice that for client side validation it needs some JavaScript for things to be styled properly.

On top of that it will take care of all the unobtrusive validation tags for you.It also offers fluent syntax, that enables full customization of the inputs/labels...

Check it out!

Disclaimer: I'm the author of TwitterBootstrapMVCAs of Bootstrap 3 (and TwitterBootstrapMVC 3) TwitterBootstrapMVC requires a licence for usage.


I took the liberty and created an extension method that encapsulates the code from Sherbrow to render the error class when the field is not valid. This extension method has the advantage that it is strongly-typed and shorter to write:

public static MvcHtmlString ModelStateFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)    {        var modelMetadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);        if (html.ViewData.ModelState.IsValidField(modelMetadata.PropertyName))        {            return MvcHtmlString.Empty;         }        return new MvcHtmlString("error");    }