简体   繁体   English

将字符串从db解析为HTML

[英]Parse string from db to HTML

I came over the following problem during creating my homepage. 我在创建主页时遇到了以下问题。

I have a database which contains a comment from an user. 我有一个包含用户评论的数据库。 This comment should be able to contain HTML elements for formatting and high flexibility. 此注释应该能够包含HTML元素以进行格式化和高度灵活性。

Text in database cell (Type: ntext): 数据库单元格中的文本(类型:ntext):

Hi, I'm a <b>Comment</b>

Code in .cshtml file: .cshtml文件中的代码:

<p>@textfromdb</p>

What is displayed on the website: 网站上显示的内容:

Hi, I'm a <b> Comment </b> 嗨,我是<b>评论</b>

What should be displayed on the website: 应该在网站上显示什么:

Hi, I'm a Comment 嗨,我是评论

Is it possible to somehow render that string to a valid HTML string? 是否有可能以某种方式将该字符串呈现为有效的HTML字符串? I sadly did not found any useful information on Google, mainly due to a lack of the right keywords I think. 遗憾的是,我没有在Google上找到任何有用的信息,这主要是因为我认为缺少合适的关键字。

Thanks for your help! 谢谢你的帮助!

请尝试以下方法:

 @Html.Raw(textfromdb)

This might not be the correct way to do it since I don't work with razor (so im fudgy on whats supported and not) but this is a way to do it in old style asp.net/C# 这可能不是正确的方法,因为我不使用剃刀(所以我很喜欢什么样的支持而不是)但是这是一种在旧式asp.net/C#中做到这一点的方法

So here is my implementation, i use panels(this is what i don't know if exist in razor) when i need to send HTML directly from server to page. 所以这是我的实现,当我需要直接从服务器发送HTML到页面时,我使用面板(这是我不知道是否存在于剃刀中)。

Server side: 服务器端:

PanelID.Controls.Add(new LiteralControl("<p>Hi, I'm a <b>Comment</b></p>"));

Client Side: 客户端:

<asp:Panel ID="PanelID" runat="server"></asp:Panel>

Output would then be 那么输出就是

Hi, I'm a Comment 嗨,我是评论

If this is a poor way of doing it, i would only welcome an alternate (but i haven't found a better one yet). 如果这是一个糟糕的做法,我只欢迎一个替代(但我还没有找到一个更好的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM