ASP.NET 4.0- Html Encoded Expressions

Posted by Jalpesh P. Vadgama on ASP.net Weblogs See other posts from ASP.net Weblogs or by Jalpesh P. Vadgama
Published on Sat, 08 Jan 2011 12:16:47 GMT Indexed on 2011/01/08 12:54 UTC
Read the original article Hit count: 683

Filed under:
|
|
|
|

We all know <%=expression%> features in asp.net. We can print any string on page from there. Mostly we are using them in asp.net mvc. Now we have one new features with asp.net 4.0 that we have HTML Encoded Expressions and this prevent Cross scripting attack as we are html encoding them.

ASP.NET 4.0 introduces a new expression syntax <%: expression %> which automatically convert string into html encoded. Let’s take an example for that.

I have just created an hello word protected method which will return a simple string which contains characters that needed to be HTML Encoded. Below is code for that.

protected static string HelloWorld()
{
    return "Hello World!!! returns from function()!!!>>>>>>>>>>>>>>>>>";
}
Now let’s use the that hello world in our page html like below. I am going to use both expression to give you exact difference.
<form id="form1" runat="server">
<div>
    <strong><%: HelloWorld()%></strong>
</div>
<div>
    <strong><%= HelloWorld()%></strong>
</div>
</form>

Now let’s run the application and you can see in browser both look similar.

HtmlEncodedExpression

But when look into page source html in browser like below you can clearly see one is HTML Encoded and another one is not.

HtmlEncodeView with html encoding

That’s it.. It’s cool.. Stay tuned for more.. Happy Programming

Technorati Tags: ,,
Shout it

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about c#.net