ASP.NET MVC Passing Raw HTML from Controller to View

人盡茶涼 提交于 2019-12-03 15:06:17

<%: means "encode if necessary". If you don't want that, then the lazy approach would be to use <%=, but frankly I suggest you instead wrap it in IHtmlString, for example:

string yourEncodedHtml = ...
var html = new MvcHtmlString(yourEncodedHtml);

Now, if you store that and show it, it should take the html "as is".

Try using: <%= %>

<%= Html.Raw(ViewData["HTMLData"].ToString())%>

<%: %> is Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC)

For More Details

How to HTML Encode Content Today

ASP.NET applications (especially those using ASP.NET MVC) often rely on using <%= %> code-nugget expressions to render output. Developers today often use the Server.HtmlEncode() or HttpUtility.Encode() helper methods within these expressions to HTML encode the output before it is rendered.

While this works fine, there are two downsides of it:

It is a little verbose Developers often forget to call the Server.HtmlEncode method – and there is no easy way to verify its usage across an app

New <%: %> Code Nugget Syntax

With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so. This eliminates the need to explicitly HTML encode content.

We chose the <%: %> syntax so that it would be easy to quickly replace existing instances of <%= %> code blocks. It also enables you to easily search your code-base for <%= %> elements to find and verify any cases where you are not using HTML encoding within your application to ensure that you have the correct behavior.

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