Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit Login control button when I hit Enter

I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.

The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well if the page has a master page. I've tried setting the default button in code with control.ID, control.ClientID, and control.UniqueID, and in each case I get:

The DefaultButton of panelName must be the ID of a control of type IButtonControl.

I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?

like image 867
Ryan Lundy Avatar asked Oct 14 '08 16:10

Ryan Lundy


3 Answers

This should be helpful: http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx

You can use the following to reference the button within the Login control template:

DefaultButton="Login$LoginButton"

Basically, you can define a DefaultButton not just on the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit "Enter"

like image 160
Vassili Altynikov Avatar answered Nov 04 '22 00:11

Vassili Altynikov


Great answer by Blend Master! Essentially just use Panel.DefaultButton, but I want to clear up the confusion about what exactly you need to set it to. It's not just ".ID" or ".UniqueID" - the documentation is a bit lacking on this.

You must set it to the UniqueID of the button, relative to the Panel's naming container UniqueID. For example, if your panel UniqueID is"Body$Content$pnlLogin" and your login button's UniqueID is "Body$Content$ucLogin$btnLogin" (because it's inside a control called "ucLogin") then you need to set Panel.DefaultButton to "ucLogin$btnLogin".

You can work this out in code as follows. (I couldn't find any class library method for this, but let me know if you find one.)

void SetDefaultButton(Panel panel, IButtonControl button)
{
    string uniqueId = ((Control)button).UniqueID;
    string panelIdPrefix = panel.NamingContainer.UniqueID + Page.IdSeparator;

    if (uniqueId.StartsWith(panelIdPrefix))
    {
        uniqueId = uniqueId.Substring(panelIdPrefix.Length);
    }

    panel.DefaultButton = uniqueId;
}
like image 27
EMP Avatar answered Nov 04 '22 01:11

EMP


you have to add something like this in page load...

txtPassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + lnkSubmit.UniqueID + "','')")

the password textbox has an onKeyPress attribute added that will force a doPostBack on the submit button if the "Enter" key is pressed. This simulates clicking the submit button.

like image 32
StingyJack Avatar answered Nov 04 '22 02:11

StingyJack