HTML Encoding in MVC

One of the best features in the Razor View Engine that I like most is "HTML Encoding". In many cases (like a comment form in a blog) we receive the data from users and he may be trying to harm us by sending some malicious scripts to cause cross-site script injection attacks (aka XSS attack).
In ASP.NET Web Forms we have a couple of ways to do HTML encoding:

ASP.NET 3.5 and below: <%= Html.Encode(data to encode) %>
ASP.NET 4: <%: data to encode %>

The above approaches help us in mitigating Cross Site Scripting (XSS) attacks in ASP.NET Web Forms.

ASP.NET MVC Razor expressions are automatically HTML encoded. It is always a good practice to validate data received from a user before storing it in the database because the database can accept any malicious data, especially XSS data happily but if you are using Razor to display the data on the web page then you are still safe and you don't need any special care.

Let's look at the following image:

MVC1.png

 

In the above image, you can see we have a peice of data which is not encoded. But I'm a proud Razor programmer because it handles HTML encoding automatically, here it is:

 

MVC2.png

 

However, sometimes we need to display the HTML markup as it is on the web page, then use Html.Raw.
 

MVC5.png

 

Note: Sometimes we need to display user input within JavaScript; we then use @Ajax.JavaScriptStringEncode to encode the input. For example:
 

<script type="text/javascript">

$(function () {

var message = 'Message is : @Ajax.JavaScriptStringEncode(ViewBag.Message)';

$("#divmsg").html(message);

});

</script>

Up Next
    Ebook Download
    View all
    Learn
    View all