ASP.NET MVC - Adding XHTML to Validation Error Messages

Just starting with ASP.Net MVC and hit a bit about validation messages. I have a special validation attribute assigned to my class to validate several properties in my model.

If this check fails, we would like the error message to contain XHTML markup, including a link to the help page (this was done in the original WebForms project as ASP: Panel).

Currently, XHTML tags, such as "<a>", are displayed on the screen in ErrorMessage. Is there a way to get ValidationSummary to correctly display XHTML markup? Or is there a better way to handle this check?

thanks

+4
source share
5 answers

OK, thanks tvanfosson for the offer to see the source code.

I essentially flipped my own helper "Html.ValidationSummaryXHTML", which did not HtmlEncode output any error message in ModelState, just delayed until "InnerHtml".

It works with pleasure!

-1
source

Here's a short fix that uses HtmlDecode () to cancel the encoding. It works for me.

(It was not possible to reinstall the entire model of the Validation object.)

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())); } } 
+7
source

I am sure that hash messages for authentication by default HTML encode any message that may be in your attribute. My suggestion would be to use the source code available in CodePlex as a starting point for writing your own HtmlHelper extension, which does not encode HTML code on an error string. You want to look in the System.Web.Mvc.Html namespace of the ValidationExtensions.cs file.

+2
source

In the end, I just got the output of ValidationSummary and just HtmlDecode.

Works great with ModelState errors in html, and I don't need to create my own ValidationSummary.

 public static MvcHtmlString ValidationSummaryNoEncode(this HtmlHelper htmlHelper) { string validationSummaryOutput = htmlHelper.ValidationSummary().ToHtmlString(); string decodedValidationSummaryOutput = HttpUtility.HtmlDecode(validationSummaryOutput); return MvcHtmlString.Create(decodedValidationSummaryOutput); } 
+2
source

You can also use the helper methods Html.Raw and HttpUtility.HtmlDecode in the view to render validation messages containing HTML markup. Here is 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())) 
0
source

Source: https://habr.com/ru/post/1304692/


All Articles