Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

asp.net - How does Html.Raw MVC helper work?

I use the Html.Raw to print a raw html content, for example when I send some thing like ViewBag.div = "<div> Hello </div>"; from the controller to the view side it does not print a raw html content unless I use the Html.Raw method but if I have an encoded content, like content encoded using jquery and inserted into the database and I want to print it as a raw html content the Html.Raw method does not work and I have to use HttpUtility.HtmlDecode(EncodedContent) before I use Html.Raw so please could anyone explain why it acts in this way and what is the proper situation to use Html.Raw method? or in another way, why Html.Raw does not work when it receives html entities as a parameter instead of html tags?.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Because encoded characters are HTML, and the Raw version of that string is the encoded one.


Html.Raw renders what it is given without doing any html encoding, so with ViewBag.div = "<div> Hello </div>";:

@Html.Raw(ViewBag.div);

Renders

<div> Hello </div>

However, when you have encoded characters in there, such as ViewBag.Something = "&gt;"; the raw version of that is &gt;. To get back to actual html you need to Html.Raw(HttpUtility.HtmlDecode(EncodedContent)); as you've said.

If Html.Raw did do the decoding then it would be confusing, and we would need something that didn't do it. ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...