0

I am using C# ASP.NET MVC, and wish to populate a DIV with html stored in a database. I have tried the following:

//getting a string of HTML from a database
@{
string myHtml = Model.Data.Html;
}

//Using Javascript to insert this into a Div
<script>
$("#myDiv").html("@myHtml");
</script>

The div fills with the html, but it is inserted as raw text and displays all of the html tags. I have tried .append and .html to no avail.

Any help would be appreciated.

3 Answers3

3

Maybe you want to use the @Html.Raw() method?

$('#myDiv').html('@Html.Raw(myHtml)');

Be careful as this could be part of an XSS vulnerability. Don't directly render user input as unencoded HTML. (This is exactly why the ASP.NET MVC Framework HTML-encodes output by default, which is the issue you're seeing.)

David
  • 208,112
  • 36
  • 198
  • 279
0

Try

 $("#myDiv").html('@Html.Raw(Model.Data.Html)')
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
0

If you don't have an explicit requirement to use Javascript to do this, simply use Html.Raw to output unencoded HTML inline.

<div id="myDiv">@Html.Raw(myHtml)</div>
Tom Bowers
  • 4,951
  • 3
  • 30
  • 43