Using html in ErrorMessage property of data annotations

时光总嘲笑我的痴心妄想 提交于 2019-12-22 11:09:08

问题


Anyone know if it is possible to do the following:

public class User
{
    public Guid UserID { get; set; }

    [Required(ErrorMessage="A school selection is required.")]
    [Range(1, int.MaxValue, ErrorMessage="School not found.  Please contact support at <a href='mailto:support@mysite.com'>support@mysite.com</a>")]
    public int SchoolID { get; set; }

    // ... other properties
}

And not have @Html.ValidationMessageFor(model => model.SchoolID) encode the HTML? Maybe I need to make a custom helper extension for this? Is there an easier way? Any guidance would be appreciated. If a helper extension is the way to go, how could I access the validation rules in the helper extension method to make sure the html doesn't get encoded?

Thanks.


回答1:


Depending on how often you needed to use this, you could use the HttpUtility.HtmlDecode method on the validation message.

@{HttpUtility.HtmlDecode(Html.ValidationMessageFor(x=>x.SchoolId).ToString)}

The more reusable, but more upfront time involved method would be to create your own html helper (maybe called HtmlValidationMessageFor()) that returns a non-html encoded string.

With that said, the return type for the ValidationMessageFor function is an MvcHtmlString which states that it is

Represents an HTML-encoded string that should not be encoded again.

But I could not find a solid reason as to why this should not be encoded again except that it may be a double encoded string.




回答2:


I did some more searching and came across the SO post below that addresses how to do what I am asking. I've added that answer here in case anyone comes across this in the future. I'm going to mark this as the answer as well since it is closest to the best answer I was looking for, but I'll let the moderators decide if this needs to be closed as a duplicate.

Render HTML tags inside of HTML.ValidationMessageFor in MVC3




回答3:


I just needed a workaround for one error message. So a simple jquery detour;

 <script>
    $(document).ready(function() {
       $('.validation-summary-errors ul li').each(function(){
            if($(this).html() == "School not found"){
                $(this).html("School not found.  Please contact support at <a href='mailto:support@mysite.com'>support@mysite.com</a>");
            }
       });
    });

Cheers!



来源:https://stackoverflow.com/questions/11871495/using-html-in-errormessage-property-of-data-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!