Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Html code with razor

I've searched over this website and I've looked over similar questions and i did not find the answer, I am sure it is somewhere but i did not find it, I have a string like this one for example :

string inputText = "<strong>Hello World</strong>"

This string comes from a certain request in control, and i have no power to change the model or the control. I can only change my razor view, using Html.Raw displays this result :

<strong>Hello World</strong>

And the result i want to be displayed is this one :

Hello World

How is it possible ?

PS: this is only a simple example, it can be any HTML Code.

like image 956
Mehdi Souregi Avatar asked Dec 01 '16 13:12

Mehdi Souregi


People also ask

How do I render in HTML?

The Render FunctionThe ReactDOM.render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

Why you should never use HTML raw in your Razor views?

Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.


2 Answers

You should use:

@Html.Raw(HttpUtility.HtmlDecode(inputText))

Decode and then render in html

like image 83
Ionut N Avatar answered Oct 16 '22 16:10

Ionut N


To render any string (which includes HTML tags) -received from the model- as HTML, use:

@Html.Raw(Model.SomeString)
like image 41
Mohammed Noureldin Avatar answered Oct 16 '22 16:10

Mohammed Noureldin