Just starting with ASP.Net MVC and have hit a bit of a snag regarding validation messages. I've a custom validation attribute assigned to my class validate several properties on my model.
When this validation fails, we'd like the error message to contain XHTML mark-up, including a link to help page, (this was done in the original WebForms project as a ASP:Panel).
At the moment the XHTML tags such as "< a >", in the ErrorMessage are being rendered to the screen. Is there any way to get the ValidationSummary to render the XHTML markup correctly? Or is there a better way to handle this kind of validation?
Thanks
Here's a short-term fix that uses HtmlDecode() to reverse the encoding. Works for me.
(Couldn't be bothered rebuilding the whole Validation object model.)
public static class ValidationExtensions
{
public static MvcHtmlString ValidationMessageHtmlFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
return new MvcHtmlString(
HttpUtility.HtmlDecode(
htmlHelper.ValidationMessageFor<TModel, TProperty>(
expression,
null,
((IDictionary<string, object>)new RouteValueDictionary()))
.ToHtmlString()));
}
}
I'm pretty sure that the default validation message helpers HTML encode any message that you might have in your attribute. My suggestion would be to use the source code available on CodePlex as a starting point to write your own HtmlHelper extension that doesn't do HTML encoding on the error string. You want to look in the System.Web.Mvc.Html namespace for the ValidationExtensions.cs file.
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