Link for code samples used in the demo
Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists
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
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”);
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
Xem Thêm Bài Viết Khác:https://wijstaanvooronzegrondrechten.org/cong-nghe