Thursday, April 15, 2010

HtmlEncode() Without The HtmlEncode()

<script runat="server" language="c#">
  protected string BadHtml = "<script language='javascript'>alert('Hello');</script>";
</script>
<%=BadHtml%>


The code above would cause an alert box to pop saying “Hello” because it is not HTML encoded.  Typically what you might do here is use the Server.HtmlEncode() method within a property and use that instead.  But now with C# 4.0 & Visual Studio 2010 you can just write this:



<script runat="server" language="c#">
    protected string BadHtml = "<script language='javascript'>alert('Hello');</script>";
</script>
<%:BadHtml%>


Notice the “:” instead of “=”.  This will automatically do the encode for you.  Saving keystrokes is great!

No comments:

Post a Comment