Search code examples
c#asp.netgridviewupdatepanelhtml-encode

Javascript Breaking on < & > in a GridView edit box


I've got an Asp.Net GridView inside an UpdatePanel. It all works fine, except when one of the columns includes HTML special characters like < and >. The GridView is bound to a List<Entity> and the Entity class has a property Regex which is a System.Text.RegularExpressions.Regex.

At first I had this:

<asp:TemplateField HeaderText="RegEx">
    <ItemTemplate>
        <asp:Label ID="RegExLabel" runat="server" Text='<%#Eval("Regex") %>' 
                   ToolTip='<%#Eval("Regex") %>' Width="102px" CssClass="Wrap" />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="RegExTextBox" runat="server" Text='<%#Eval("Regex") %>' 
                     Width="98px" />
    </EditItemTemplate>
</asp:TemplateField>

With a value of (?<capture>\d+) this displayed ?\d+ when not editing, and when editing this row I got a script error and the edit, update and cancel buttons no longer work.

Then I tried the answer in this question and had this:

<asp:TemplateField HeaderText="RegEx">
     <ItemTemplate>
          <asp:Label ID="RegExLabel" runat="server" 
                     Text='<%#System.Web.HttpUtility.HtmlEncode(Eval("Regex").ToString()) %>' 
                     ToolTip='<%#System.Web.HttpUtility.HtmlEncode(Eval("Regex").ToString()) %>'
                     Width="102px" CssClass="Wrap" />
     </ItemTemplate>
     <EditItemTemplate>
          <asp:TextBox ID="RegExTextBox" runat="server" 
                       Text='<%#System.Web.HttpUtility.HtmlEncode(Eval("Regex").ToString()) %>' 
                       Width="98px" />
     </EditItemTemplate>
</asp:TemplateField>

This is slightly better, in that the tooltip and the non-editing version display correctly, but when I start editing I see: (?&lt;capture&gt;\d+) with the HTML Entities displayed raw. Does anyone know a way to encode the values (to stop the script error) while still displaying them correctly without the HTML entities in their raw state when editing?


Solution

  • <asp:TemplateField HeaderText="RegEx">
        <ItemTemplate>
            <asp:Literal Mode="Encode" ID="RegExLabel" runat="server" Text='<%#Eval("Regex") %>' 
                       ToolTip='<%#Eval("Regex") %>' Width="102px" CssClass="Wrap" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="RegExTextBox" runat="server" Text='<%#Eval("Regex") %>' 
                         Width="98px" />
        </EditItemTemplate>
    </asp:TemplateField>
    

    and in the page directive add this ValidateRequest="false"