Part 49 Html encoding in asp net mvc

preview_player
Показать описание
Link for code samples used in the demo

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

In this video, 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.

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("src", VirtualPathUtility.ToAbsolute(src));
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, the image is rendered as expected.

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.

@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.

For techniques to avoid automatic html encoding, please visit my blog using the link below
Рекомендации по теме
Комментарии
Автор

Thanks so much for taking the time to make these tutorials. After the MVC video series, what do you plan on doing next? Entity Framework, perhaps?

karrncares
Автор

are there ready files for visual studio ? great tutorial btw

pawewy
Автор

sir will you teach us a LAMBDA expression in depth, please sir its a request from heart...

kiranpedamkar
Автор

sir there is must to have foreign key constraint on the table where we want to join those two or more table. and how to join more than two tables...

kiranpedamkar
Автор

sir haven't able to answer the question in interview that was what is an thread and multiThread in C#. Master Pages in Asp.net

kiranpedamkar
Автор

Can u show how to encrypt URL (URL Encryption) in mvc 3

TheSachin
welcome to shbcf.ru