Home > .NET > .Net 4 encoding and GridView

.Net 4 encoding and GridView

2012/12/28

A big change in .NET 4 is the automatic encoding of char 39 (a complete list in this page).

But this causes a problem for inserting a string in a message: for example if we want from the user a confirmation, is a good practice to insert some info from the row in the gridview that we want to delete.

For example we can have an addresses list in a asp:GridView like this :


The last icon is a typical icon for delete , in code we can have something as:

<asp:TemplateField  HeaderText="">
    <ItemTemplate>
        <a href="javascript:void(0);" onclick="deleteRecord(<%# Eval("IDaddr") %>, '<%# HttpUtility.HtmlEncode(Eval("Address").ToString()) %>')" title="Delete">
            <img src="jquery-ui-1.9.1.custom/assets/ico/cross.png" alt="" style="border-style: none;" />
        </a>
    </ItemTemplate>
</asp:TemplateField>

The encoding is requested otherwise we will see nasty effects on our page , but at runtime the js code is not rendered correctly:


Note that the string begins with ‘ but after the 5 (before “Street”) there is the char 39 that closes the string , so the remaining string is junk for the browser and the link does not work.

HttpUtility.HtmlEncode has correctly translated “5′” in “5'” but at runtime the ' is decoded back in the char, and we are using this char as delimiter for the javascript command…

The problem can be resolved translating the encoded char 39 in a escaped string , i have created a static utility class ConfigurationService where i have write

public static string EncodeString(string field)
{
    return HttpUtility.HtmlEncode(field).Replace("'", "\\'");
}

The aspx then is changed in

<asp:TemplateField  HeaderText="">
    <ItemTemplate>
        <a href="javascript:void(0);" onclick="deleteRecord(<%# Eval("IDaddr") %>, '<%# ConfigurationService.EncodeString(Eval("Address").ToString()) %>')" title="Delete">
            <img src="jquery-ui-1.9.1.custom/assets/ico/cross.png" alt="" style="border-style: none;" />
        </a>
    </ItemTemplate>
</asp:TemplateField>

And in the deleteRecord javascript function my window.confirm now can say


Advertisements
Categories: .NET
%d bloggers like this: