Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a Panel's DefaultButton property work?

What is happening when you declare a Button to be used as the DefaultButton in an ASP.NET Panel? I understand that ASP.NET will render the contents of the Panel to a div and pass a bunch of stuff to the ViewState. Is there JavaScript inside the ViewState that handles the rendered Button's click event? I thought ViewState was just that - info about state. How does it work?

like image 777
notAnonymousAnymore Avatar asked Jul 02 '13 21:07

notAnonymousAnymore


1 Answers

You're right about the ViewState. It's designed to keep Page and Controls values. That is, their state. You can confirm it here.

About the default button, there is no magic. A javascript is added to the div in order to bind the ENTER key event.

Let's check it out! This code:

<asp:Panel ID="panel" runat="server" DefaultButton="button">
    <asp:Button ID="button" runat="server" Text="this is the button" />
</asp:Panel>

Is rendered to this:

<div id="panel" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'button')">
  <input type="submit" name="button" value="this is the button" id="button">          
</div>

This javascript is generated by the WebForms engine, but we can look for it, if you're curious:

function WebForm_FireDefaultButton(event, target) {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton;
            if (__nonMSDOMBrowser) {
               defaultButton = document.getElementById(target);
            }
            else {
                defaultButton = document.all[target];
            }
            if (defaultButton && typeof(defaultButton.click) != "undefined") {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    return true;
}

Notice how it tests if the currently focused control is a textarea. This is because an ENTER inside a textarea is mostly a new line, not a submit.

like image 131
Andre Calil Avatar answered Oct 24 '22 14:10

Andre Calil