Escape Special Characters

Escape Special Characters in Kentico 13

In C# and Razor views (Kentico 12/13), you can escape special characters by using the Html.Raw() method or the @Html.Raw() helper in Razor syntax. This method allows you to render raw HTML or content without HTML encoding.

For example, if you have a string containing HTML or special characters and you want to display it as raw HTML in a Razor view, you can use Html.Raw() like this:

@{
    // Your string containing HTML or special characters
    string contentWithSpecialChars = "<p>This is a <strong>sample</strong> content &amp; more.</p>";

    // Display the content without encoding HTML
    @Html.Raw(contentWithSpecialChars)
}

The Html.Raw() method will render the HTML tags and display the content as intended without encoding special characters like <, >, &, etc.

But, what if you need to encoded special characters for use in JavaScript on C# and Razor views?

In ASP.NET and Razor views, you can escape special characters using HttpUtility.JavaScriptStringEncode in C# to ensure that strings are properly encoded for use in JavaScript.

Here’s an example of how you can use HttpUtility.JavaScriptStringEncode in a Razor view:

@{
    // Your string containing special characters
    string stringWithSpecialChars = "This is a string with \"quotes\", 'single quotes', and backslashes \\";

    // Encode the string for JavaScript
    string encodedString = System.Web.HttpUtility.JavaScriptStringEncode(stringWithSpecialChars);
}
<script>
    var encodedString = @Html.Raw(Json.Encode(encodedString));
    // Use the encoded string in JavaScript
    console.log(encodedString);
</script>

In the above code:

stringWithSpecialChars is the string that contains special characters.
System.Web.HttpUtility.JavaScriptStringEncode encodes the string for use in JavaScript.
@Html.Raw(Json.Encode(encodedString)) in the script block is used to output the encoded string as raw JavaScript.

This method ensures that special characters within the string are properly escaped for use in JavaScript strings, preventing syntax errors and potential security vulnerabilities, such as injection attacks when the string is inserted into JavaScript code.

If you only need to escape special characters for use in JavaScript on the Razor view, you can simplify it by skipping the script and Json.Encode part:

@{
    // Your string containing special characters
    string stringWithSpecialChars = "This is a string with \"quotes\", 'single quotes', and backslashes \\";

    // Encode the string for JavaScript
    string encodedString = System.Web.HttpUtility.JavaScriptStringEncode(stringWithSpecialChars);
    @encodedString
}