Integrating Twitter Bootstrap with Asp.net MVC 3 forms

17,216

Solution 1

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).

Solution 2

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 TwitterBootstrapMVC As of Bootstrap 3 (and TwitterBootstrapMVC 3) TwitterBootstrapMVC requires a licence for usage.

Solution 3

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");
    }
Share:
17,216

Related videos on Youtube

Agares
Author by

Agares

write all teh codez in all teh languages

Updated on September 15, 2022

Comments

  • Agares
    Agares over 1 year

    I am using Asp.net 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 HtmlHelper 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>
       </div>
    </div>
    

    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 LabelFor, EditorFor and ValidationMessageFor. Is there a simpler way to do this? And what about the unobtrusive validation?

    • baynezy
      baynezy almost 12 years
      Did you get anywhere with this? I am attempting this too
    • Agares
      Agares almost 12 years
      I haven't found anything in the internet about it. I'm probably gonna end up doing this by myself.
    • baynezy
      baynezy almost 12 years
      I am going to do it myself. Once I've got something on GitHub I'll post the link here.
    • Agares
      Agares almost 12 years
      That would be really great. Thank you very much :).
    • baynezy
      baynezy over 11 years
      I have started a project on GitHub github.com/baynezy/MVC.Bootstrap which does this. I have currently added in support for TextBox, Password and TextArea. I hope this is of some help.
  • Sherbrow
    Sherbrow over 11 years
    Nice, why don't you make an edit of my answer including your code and replacing the error class test ?
  • A. Murray
    A. Murray over 10 years
    As of Bootstrap 3 (and TwitterBootstrapMVC 3) TwitterBootstrapMVC requires a licence for usage.
  • Jose
    Jose over 10 years
    @Dmitry, I am using your method here, and the validation pops up, but with no styling whatsoever, I have not messed with the css files in any way (just installed the nugget package). Is there anything else besides what you wrote that needs to be done? If not, what things could check out for?
  • Jose
    Jose over 10 years
  • Dmitry Efimenko
    Dmitry Efimenko over 10 years
    @Jose, You are probably not seeing styling on client side validation. Is that right? the @Html.Bootstrap().ValidationSummary() method was recently updated to take care of that. It now requires some JavaScript for the client validation to get styled appropriately. You can get this Javascript here. I'll reflect this info in the answer.
  • Jose
    Jose over 10 years
    I see, I just added an extra css line, which seemed to work fine (for styling) but I'm assuming this only works for TwitterBootstrapMVC 3 ? CSS: .alert-error, .validation-summary-errors { color: #b94a48; background-color: #f2dede; border-color: #eed3d7; }
  • Dmitry Efimenko
    Dmitry Efimenko over 10 years
    Yeah, TwitterBootstrapMVC 3 has ValidationSummary completely rebuilt. If you "inspect element" in developer tools you'll see that the whole thing is now wrapped in a div with a special class "bmvc-[version]-validation-summary". If you still have an issue with this, please create an issue on GitHub and we'll discuss it there