Using Html.Raw and Strongly Typed Models together

In C#, @Html.Raw() is a method often used in ASP.NET MVC or ASP.NET Core applications when you need to output HTML content directly to the view without HTML encoding.

By default, when you output text or content in a view, ASP.NET will automatically encode HTML characters like <, >, &, etc., to prevent cross-site scripting (XSS) attacks and ensure security. However, there are scenarios where you might need to output HTML markup that you want to be rendered as HTML and not encoded.

Today I had a scenario when I had to use @Html.Raw() but I also needed to inject a value from a strongly typed model. 

Below is the code that I had initially

@Html.Raw("<div class=\"tv-video site-video\" id=\"section-@Model.Content.ContentType.Alias\" >");

However, this output in the browser:

<div class=\"tv-video site-video\" id=\"section-@Model.Content.ContentType.Alias\" >

You can see that @Model.Content.ContentType.Alias is not what I want to be here, it should be the Alias name e.g. id="section-videoBlock"

To fix this, I needed to change the code to this:

@Html.Raw($"<div class=\"tv-video site-video\" id=\"section-{Model.Content.ContentType.Alias}\" >");

In this code snippet, the Model.Content.ContentType.Alias is injected into the HTML string using the $ symbol to denote string interpolation in C#. This ensures that the value of Model.Content.ContentType.Alias is properly inserted into the HTML string while escaping the Html.Raw method.

Published on : 14 March 2024