简体   繁体   中英

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.

Text in database cell (Type: ntext):

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

Code in .cshtml file:

<p>@textfromdb</p>

What is displayed on the website:

Hi, I'm a <b> Comment </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? I sadly did not found any useful information on Google, mainly due to a lack of the right keywords I think.

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#

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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