views:

361

answers:

2

I have a pretty simple ASP.NET Web Form that looks a bit like the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="example.aspx.cs" Inherits="example" %>

<form runat="server">
    <asp:GridView runat="server" id="grid" AutoGenerateColumns="false" OnRowCommand="DoStuff">
        <Columns>
            <asp:ButtonField Text="Do stuff" />
        </Columns>
    </asp:GridView>
</form>

(In PageLoad I call grid.DataBind(), and the event handler DoStuff is unremarkable.)

When I view this in Internet Explorer and click the ButtonField (which renders as a link), the event handler fires as expected. When I click it in Firefox, nothing happens.

If I turn on Firebug's Javascript debugging console then click the link, it shows an error in the Javascript onclick handler that's auto-generated by ASP.NET:

theForm is undefined
__doPostBack("grid", "$0")
javascript:__doPostBack('grid', '$0')()
  if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\r\n

Why does this happen and how can I make the ButtonField work in Firefox?

(N.B. I'm asking this question in order to answer it myself: I've already discovered why I was seeing the above error, and wanted to record it for the benefit of myself and others. Feel free to add other answers if you know other gotchas with ASP.NET and Firefox.)

A: 

This is due to a difference in how the browsers handle Javascript in the presence of invalid HTML: specifically, when the form is not surrounded with <html> and <body> tags. Without these tags, Firefox seems to try to initialise the variable theForm before the form actually exists.

Adding the proper <html> and <body> tags around the form (as is required for valid HTML in any case) makes the click handler work in both IE and Firefox.

Notes:

  • obviously invalid HTML is a worst practice for many other reasons. The page I was developing was intended to be used with a Master page which rendered the rest of the surrounding HTML, but (for various reasons) I was testing it in isolation from the Master page.
  • I tried reproducing the same problem with a simple <asp:Button runat="server">, but that triggers a full page-refreshing PostBack, so it doesn't hit the same error. Being a Web Forms n00b I don't know what's special about a GridView (or this use case) that makes it behave differently (i.e. sets up an onclick handler to handle the click without a page load).
  • I've marked this as wiki in case anyone else can explain this better than I.
Sam Stokes
A: 

thanks,i solve my problem,cheers!

Ray