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
300 views
in Technique[技术] by (71.8m points)

c# - How to render encoded tags as proper HTML, rather than text?

I'm getting the following text from a database: (supplied by client, so I can't do much with it)

investment professionals.<BR /><BR /> blah blah blah

which is getting rendered as:

investment professionals.<BR /><BR /> blah blah blah

I don't want to print the <BR /> tags on the screen. I want them to behave as actual breaks.

The following Html Helper code builds the span it exists in, adds that to a div and returns the HTML string:

StringBuilder sbElements = new StringBuilder();

TagBuilder span = new TagBuilder("span") {InnerHtml = subject.AboutText};
sbElements.Append(span.ToString());

TagBuilder div = new TagBuilder("div");
div.MergeAttribute("class", "about-text");
div.InnerHtml = sbElements.ToString();

return div.ToString();

If I Html.Encode() the output of the helper method, the encoded tags - /&gt;&lt; - get written to the screen. How can I take the source text I have and ensure that the tags get rendered as HTML, rather than text?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are using Razor, it will doubly-encode your string as @Chevex described. If you use the new MVC3 <%: %> syntax, it will also doubly-encode it. Regardless of your view engine, you can work around the encoding with either the IHtmlString route (e.g., MvcHtmlString) described by @Chevex or by bypassing the default encoding using a different template syntax.

The later, which doesn't involve changing any code, just requires tweaking the syntax you use to render to a view.

For Razor:

@Html.Raw(yourvariable)

For MVC's default view template system:

<%=yourvariable%>

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

...