by Andreas

ASP.NET – Cross browser default button

We have previously covered default buttons both in Silverlight and generic ASP.NET (both in Norwegian, but the code samples know no language barriers). I thought I’d add a third post about this, because the generic ASP.NET default button only shows the simplest approach – which is not fully browser independent. It works great in Internet Explorer, but if you want to make sure it also works in other browsers like Chrome and Firefox a more thorough approach is required.

I solved this by creating a new class that inherits from System.Web.UI.WebControls.LinkButton. In the OnLoad event, a script is added to the page which handles the click event for the link button. I would add a reference to the source of the script if I had it, but unfortunately that’s long gone.

Create a new class called LinkButtonDefault.cs and add the following code:

using System;
using System.Web.UI.WebControls;

namespace My.Very.Own.Namespace
{
    public class LinkButtonDefault : LinkButton
    {
        protected override void OnLoad(System.EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "addClickFunctionScript",
                _addClickFunctionScript, true);

            string script = String.Format(_addClickScript, ClientID);
            Page.ClientScript.RegisterStartupScript(GetType(), "click_" + ClientID,
                script, true);
            base.OnLoad(e);
        }

        private const string _addClickScript = "addClickFunction('{0}');";

        private const 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.getAttribute('href')); }}
            }}}};";
    }
}

 

At the top of the page where you want your custom default link button, register the component and give it a tag prefix:

<%@ Register TagPrefix="UR" Namespace="My.Very.Own.Namespace" Assembly="Name.Of.Your.Assembly, Version=1.0.0.0,  Culture=neutral, PublicKeyToken=3011884815bf2cfd" %>

 

Replace namespace, assembly name and public key token with your corresponding values. Then create a button based on your inherited class (using the tag prefix defined in the previous step):

<UR:LinkButtonDefault ID="lnkContinue" runat="server" onclick="btnContinue_Click">

 

Wrap the button inside a panel, and set the DefaultButton parameter to your button:

<asp:Panel ID="Panel1" runat="server" DefaultButton="lnkContinue">