Search code examples
c#htmlasp.net-core

How to write HTML syntax to view in ASP.NET Core


I have content which includes HTML tags, but when I write the value to the view, it encodes it and the HTML tags are messed up.

I've tried to use HtmlDecode, but same issue.

Code:

@WebUtility.HtmlDecode(img.Description)

Data:

{
  "name": "pic1.jpg",
  "order": 2,
  "likes": 21,
  "title": "this is pic01",
  "description": "dette er<br />beskrivelse"
}

Output (HTML):

<div class="details-wrap">
    <hr style="width:60%;" />

    dette er&lt;br /&gt;beskrivelse
</div>

Solution

  • To display the HTML-decoded description in an ASP.NET Core view, you can use @WebUtility.HtmlDecode to decode the HTML string contained in img.Description. Here's how you can write the syntax in a Razor view:

    @using System.Net
    
    <div>
        <h3>@img.Title</h3>
        <p>@Html.Raw(WebUtility.HtmlDecode(img.Description))</p>
    </div>
    

    HTML output:

    <div>
        <h3>this is pic01</h3>
        <p>dette er<br />beskrivelse</p>
    </div>