Tuesday, 22 March 2011

ASP.Net: Default LinkButtons in non IE browsers

ASP.Net pages are only allowed one 'form' tag and that means multiple submissions within the page need to be handled to cover users who press 'Enter' rather than click the relevant buttons.

This is usually done by specifying the default button for a form or placing panels around content with default buttons within them.

As I've found out today though, this works perfectly for normal Button controls but not for LinkButton controls. Well, it works as expected in Internet Explorer but that's not good enough these days with Chrome and Firefox being just as popular.

Therefore, I had to do some digging and this is the code I found to cure the problem;

<script type="text/javascript">
var __defaultFired = false;

function WebForm_FireDefaultButton(event, target) {
    var element = event.target || event.srcElement;

    if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
        var defaultButton;

        if (__nonMSDOMBrowser)
            defaultButton = document.getElementById(target);
        else
            defaultButton = document.all[target];
        if (defaultButton) {
            if(typeof(defaultButton.click) != "undefined")
                defaultButton.click();
            else
                eval(unescape(defaultButton.href.replace("javascript:""")));
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            return false;
        }
    }
    return true;
}
<script>

It needs to be placed at the bottom of the page, before the 'close form' tag so that it overrides the javascript provided by the .Net Framework.

No comments:

Post a Comment