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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With