15 Feb 2015
Recently, when writing code for my blog post on drop downs, “DropDownListFor with Dictionaries in
ASP.NET MVC and why SelectList wants to kill you”, I stumbled over an interesting problem –
when using ASP.NET MVC HTML helpers, such as @Html.TextBoxFor()
and @Html.DropDownListFor()
to
render controls and @Html.ValidationMessageFor()
to render validation error messages, I realised
that ASP.NET MVC uses its own CSS classes, so no errors are getting highlighted when using Bootstrap
3.
There’s nothing wrong with MVC as such in here, as it is meant to be CSS framework agnostic, meaning you should be able to use it with any CSS framework.
To get a better understanding of the problem, have a look at this HTML that’s generated by MVC on postback. It contains an error message for a required text field.
As you can see, ASP.NET uses its own CSS classes, such as input-validation-error
(used to
highlight control with an invalid value) and field-validation-error
which contains explanatory
text for the error.
Without proper styling the above HTML looks like this:
Not too bad, but could be better. Bootstrap 3 has this awesome indication for invalid form controls, and it highlights the entire control and the error text:
So following Bootstrap’s own documentation we need to make sure that control with error has a
parent with the class of has-error
and the validation error message element needs to have the
class of text-danger
. That’s how HTML needs to look like to get proper error highlighting:
It is clear that we just need to add two puny CSS classes, but how exactly this is done depends on whether you use client-side JavaScript validation or not.
If your form is submitted to the server with no prior on-the-client JavaScript validation (old school! but it works), then you’ve got yourself the easiest of all fixed. You can just add these CSS classes whenever the page loads in the following fashion:
Most likely though you’re using in-built ASP.NET MVC’s own unobtrusive jQuery validation, in
which case we need to hook into success
and errorPlacement
events of the jQuery Validation
Plugin:
Now admittedly this is a tad hacky, I personally don’t like how our validation code assumes a number of dangerous things, such as knowledge of parameter lists for internal functions, but it works.
FluentValidation is another popular library for ASP.NET MVC, and given it integrates with standard validation, you can use solutions listed above to make it work.
Download fully tested and 100% working Visual Studio solution with the source code used in this article for FREE – just enter your name and email in the form below, and I’ll send you the download link right away.
You will also get access to all the source code for all existing and new articles on the site, and access to my mailing list, which receives handy timesaving tips on .NET Core programming.