HtmlTags within Resx displayed in @Html.ValidationMessageFor

3.3k Views Asked by At

I have the following doubt. I am considering the option to have html tags within my resx texts for localization. When I put the resources directly I can resort to:

@Html.Raw(@Resources.ResourcesFM.Error_Email)

and it works as expected. The problem is when the resource is being called by a validation message from an htmlhelper:

@Html.ValidationMessageFor(model => model.Email)

Got from an attibute:

[DataType(DataType.EmailAddress,
ErrorMessageResourceType = typeof(ResourcesFM),
ErrorMessageResourceName = "ErrorMailIncorr")]

What I am trying...

@Html.Raw(Html.ValidationMessageFor(model => model.Email))

I do not know how to get the same result as when using @html.Raw as the output from the helper is a MvcHtmlString...

Thanks

3

There are 3 best solutions below

1
On BEST ANSWER

Try this:

View:

@Html.Raw(Server.HtmlDecode(@Html.ValidationMessageFor(m => m.UserName).ToString()))

Controller Action:

ModelState.AddModelError("UserName", "This is a link <a href='http://example.com'>Google Home</a>");
8
On

Html.ValidationMessageFor html-encodes the message. But you should be able to simply call HttpUtility.HtmlDecode() on the result. Even though the result contains html tags and whatnot, the decode will simply no-op on that part of the string.

So if `Html.ValidationMessageFor(...)' returns

<span>&lt;div&gt;This is in a div&lt;/div<&gt;</span>

Then HttpUtility.HtmlDecode(Html.ValidationMessageFor(...).ToString()) will give you

<span><div>This is in a div</div></span>

It's not pretty, but it works. Your alternative is to recreate your own Validation helper version that never encodes the message.

1
On

For Localization, you may use String.Format and choose appropriate placeholder for the link

ModelState.AddModelError("UserName", String.Format("This is a link {0}", "<a href='http://example.com'>Appropriate String From a Resource</a>"));