Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net mvc - ModelState.AddModelError encodes HTML

I am noticing a weird issue when using ModelState.AddModelError to validate input on my forms. The output from Html.ValidationMessage is not the true HTML value but it's encoded value and so the CSS style is not applied to the error message.

Example:

private string errorMessage = "<span class="negative">{0}</span><br class="hid" />";
ModelState.AddModelError("title", String.Format(errorMessage, "Tab title is required"));

The output is shown as:

<span class="field-validation-error">&lt;span class=&quot;negative&quot;&gt;URL is Required&lt;/span&gt;&lt;br class=&quot;hid&quot; /&gt;</span>

This didn't use to be the case with their earlier beta's and I am not sure what approach to take here.

Thanks Nick

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is another way to do it, too, without having to create your own extension.

Say for instance we have the following in one of our controllers:

ModelState.AddModelError("Name", "<b>Please Use a Valid Person Name</b>");

We can then do the following in our view:

@if(Html.ValidationMessageFor(x => x.Name) != null){
    @Html.Raw(Html.ValidationMessageFor(x => x.Name).ToString())
}

The will prevent the error message of '<b>Please Use a Valid Person Name</b>' from being encoded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...