Friday, March 14, 2008
The ASP.NET 2.0 DefaultButton property on Form and Panel allows IE to fire a button or link when the user hits the enter key while in a form field.  The LinkButton control does not fire when the users browser is FireFox.  Several people have found creative ways to solve this problem.  I chose to take advantage of .NET 3.5 support for Extension Methods and just wrap the needed fixes into a method right on my form object.  Here is the code for you to drop into your own library.  Perhaps I will do the same for Panel when the need arises.
  
 public static class BrowserHelper
    {
         public static void DefaultLinkButton(this HtmlForm form, LinkButton defaultButton)
        {
            // Inspired by: http://kpumuk.info/asp-net/using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net/

            // Wire-up the Link Button default supported in ASP.NET
            form.DefaultButton = defaultButton.UniqueID;

            // Script to wireup a click event for FireFox
            string _addClickScript = "addClickFunction('{0}');";

            string _addClickFunctionScript =
                @"  function addClickFunction(id) {{
            var b = document.getElementById(id);
            if (b && typeof(b.click) == 'undefined') b.click = function() {{
                var result = true; if (b.onclick) result = b.onclick();
                if (typeof(result) == 'undefined' || result) {{ eval(b.href); }}
            }}}};";

            form.Page.ClientScript.RegisterStartupScript(typeof(LinkButton), "addClickFunctionScript", _addClickFunctionScript, true);

            // Execute the script when the Page loads
            string script = String.Format(_addClickScript, defaultButton.ClientID);
            form.Page.ClientScript.RegisterStartupScript(typeof(LinkButton), "click_" + defaultButton.ClientID, script, true);
        }
    }
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):