ASP.NET MVC - Add XHTML into validation error messages
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开发者_Go百科 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.
I ended up just taking the ValidationSummary output, and just HtmlDecode it.
Works great with ModelState errors in html, and I don't have to make my own ValidationSummary.
public static MvcHtmlString ValidationSummaryNoEncode(this HtmlHelper htmlHelper)
{
string validationSummaryOutput = htmlHelper.ValidationSummary().ToHtmlString();
string decodedValidationSummaryOutput = HttpUtility.HtmlDecode(validationSummaryOutput);
return MvcHtmlString.Create(decodedValidationSummaryOutput);
}
You can also use the Html.Raw
and HttpUtility.HtmlDecode
helper methods in a view to render validation messages that contain HTML markup. Here's a simple example:
Model:
[Required(ErrorMessage = "This message contains <b>HTML markup</b> code.")]
public string MyProperty{ get; set; }
View:
@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(x => x.MyProperty).ToHtmlString()))
OK, thanks to tvanfosson for the suggestion about looking at the source code.
I essentially rolled my own "Html.ValidationSummaryXHTML" helper that didn't HtmlEncode any error message in ModelState, just deferred to "InnerHtml".
Works a treat!
精彩评论