0

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!

4
  • 2
    Be aware, that having unsanitized user generated HTML code in your website is a HUGE security issue. You should never ever allow this. If your users should be allowed to style their comments, you must explicitly limit the HTML tag your users may use! Commented Sep 9, 2012 at 11:32
  • Thank you for your security advice, this is worth a tought. But in this specific case, no user of the website is able to manipulate or add any rows in the database, so its just me who is editing it at the moment. I tought of giving some users the posibility to change their text. It's not a comment function, the example was a bit irritating, sorry. Commented Sep 10, 2012 at 8:26
  • I do not mean adding/deleting rows. Your users must not be able to create (unsanitized) HTML code that is displayed on your website. They could insert JavaScript or iFrames and load malicious content from a remote location. Commented Sep 10, 2012 at 9:14
  • I'm aware of this, users are not able to do so. Thank you for your support Commented Sep 10, 2012 at 14:40

2 Answers 2

2

Try the following:

 @Html.Raw(textfromdb)
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thank you for your answer, but I prefer the more simple method posted by Dennis Traub.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.