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
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
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
text-danger. That’s how HTML needs to look like to get proper error highlighting:
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.
Subscribe to my mailing list to get handy tips on working with the framework, various libraries and all sort of surrounding stuff. I never spam, period.