是否有可能在ASP.NET MVC 3中显示来自数据库的原始HTML? [英] Is it possible to display raw Html from database in ASP.NET MVC 3?
问题描述
我在我的数据库一个表,其中的一个属性是一个HTML页面(没有HTML,头部和身体标记),我打算把它放在我的意见之一的中间 - 比方说,我称之为cotroller方法,它接受一个参数,并返回路过这个网站很大的字符串作为模型的视图。我搜索了它(并不多,我承认),发现下面的方法:
I have a table in my db where one of the properties is an Html page (without the html, head and body tags), and I intend to put it in the middle of one of my views - say, I call a cotroller method that takes an argument, and return a view passing this html big string as the model. I searched for it (not much, I admit), and found the following method:
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>
这是被发现的here在计算器的当我尝试过类似剃须刀的形式给出,我结束了这一点:
That was found here in stackoverflow. When I tried a similar razor aproach, I ended up with this:
@System.Web.HttpUtility.HtmlDecode("<h1>Test</h1>")
这是这个想法,但我的计划是不太正常工作。
That's the idea, but it didn't work quite as I planned.
推荐答案
所有你需要的是: @ Html.Raw(友仁codedHtmlFromYouDatabase)
我假设在数据库中的HTML已正确消毒(或至少是从可靠的来源),因为如果没有,你可以打开自己到跨站点脚本攻击。
I'm assuming that the html in the database has been properly sanitized (or at least from a reliable source), because if not, you could be opening yourself up to cross-site scripting attacks.
你的方法没有工作的原因是剃刀HTML恩$ c。通过默认输出$ CS(每次使用时间 @
来显示的东西)。 Html.Raw
告诉剃刀您信任的HTML和你想不编码它(因为它是已经原始的HTML)。
The reason your approach didn't work is that Razor HTML-encodes output by default (every time you use @
to display something). Html.Raw
tells Razor that you trust the HTML and you want to display it without encoding it (as it's already raw HTML).
这篇关于是否有可能在ASP.NET MVC 3中显示来自数据库的原始HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!