Part 49 - Html encoding in asp.net mvc

Leave a Comment
we will discuss
1. What is HTML encoding
2. Why would you html encode
3. How to avoid html encoding in aspx and razor views

What is HTML encoding?
HTML encoding is the process of replacing ASCII characters with their 'HTML Entity' equivalents. For example replacing
html encoding

Why would you html encode?
To avoid cross site scripting attacks, all output is automatically html encoded in mvc. We will discuss cross-site scripting attack in a later video session.

Avoiding html encoding in razor views:
Sometimes, we have to avoid HTML encoding. There are 2 ways to disable html encoding
1. @Html.Raw("YourHTMLString")
2. Strings of type IHtmlString are not encoded

Consider the following custom Image() html helper. 
public static class CustomHtmlHelpers
    public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
        TagBuilder tb = new TagBuilder("img");
        tb.Attributes.Add("alt", alt);
        return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

Notice that, this custom Image() HTML helper method returns string of type, IHtmlString. Strings of type IHtmlString are excluded from html encoding. So, when we invoke Image() helper method from a razor view as shown below, the image is rendered as expected.
@Html.Image(@Model.Photo, @Model.AlternateText)

However, if you modify the Image() method to return string of type System.String, the HTML is encoded and that's what is shown on the view, instead of actually rendering the image.
<img alt="John Smith Photo" src="/MVCDemo/Photos/JohnSmith.png" />

@Html.Raw() method can also be used to avoid automatic html encoding. Notice that, the string that is returned by Image() method is passed as the input for Raw() method, which renders the image as expected.
@Html.Raw(Html.Image(@Model.Photo, @Model.AlternateText))

Avoiding html encoding in ASPX views:
<%%> syntax will automatically encode html in aspx views. So, the following will encode and display the html, instead of rendering the image. At the moment, the custom Image() html helper method is returning string of type system.string. If you make this method return IHtmlString, then the following code will render the image instead of html encoding it.
<%: Html.Image(Model.Photo, Model.AlternateText) %>

To avoid automatic html encoding, you can use
1. <%%>
2. Html.Raw()
3. Strings of type IHtmlString are not encoded

Both the following code blocks will render the image
<%= Html.Image(Model.Photo, Model.AlternateText) %>
<%: Html.Raw(Html.Image(Model.Photo, Model.AlternateText)) %>

Different techniques to avoid automatic html encoding in MVC
avoid automatic html encoding in MVC


Post a Comment

Note: only a member of this blog may post a comment.