1

If you generate an HTML string Like

ViewBag.FinalHTML="<a href=\"http://stackoverflow.com\">StackOverFlow</a>";

and then Try to show it in View using this code:

This is the best Q&A for programming questions: @ViewBag.FinalHTML

then the result will be this:

This is the best Q&A for programming questions: <a href="http://stackoverflow.com">StackOverFlow</a>

(I know how can I do that right. I have another question!)

How does ASP.Net MVC do it?

4

1 回答 1

5

The @ function uses the HttpUtility.HtmlEncode method to safe encode everything you pass to it.

If you don't want this automatic encoding to happen use the @Html.Raw method:

@Html.Raw(ViewBag.FinalHTML)

Obviously by doing this you should make sure that this FinalHTML is absolutely never coming from an user input but is generated by you on the server. Otherwise you are opening a huge XSS hole in your website.

于 2013-01-24T09:33:50.700 回答