简体   繁体   中英

ASP.NET DefaultButton and MasterPages

In my site i have a search function in the master page (no defaultbutton set there, also not in form). in a content page, i have a login, there i use a asp panel with defaultbutton. but when i click enter on the login textbox then my site keeps going to the search event handler... What could be the reason?

Some code:

//on content page

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write(Button1.Text);
}

    <asp:Panel ID="pnl1" runat="server" DefaultButton="Button1">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:LinkButton ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
    </asp:Panel>

//on master page:

protected void btnSearch_Click(object sender, EventArgs e)
{
    if (!txtSearch.Text.Equals(""))
    {
        Response.Redirect("searchresults.aspx?search=" + txtSearch.Text);
    }
}

<div id="searchbar">
    <asp:TextBox ID="txtSearch" CssClass="searchbar-field" runat="server"></asp:TextBox>
    <asp:Button ID="btnSearch" CssClass="searchbar-btn" runat="server" Text="Zoek" OnClick="btnSearch_Click" />
</div>

OK found the solution: It is required to use Button and not LinkButton . Then it should be alright...

You just need to set the default button on the page on the page load:

You can access the button using the FindControl method of the panel (this is VB).

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Me.Form.DefaultButton = pnl1.FindControl("Button1").UniqueID

End Sub

Found the problem, i think it is required to use Button and NOT LinkButton . Then it should be alright.

In the markup of any pages that load your login control, you need to update the html in two places.

First, in the page's form tag, you need to set the default button. See below for how I came up with the name.

<form id="form1" runat="server" defaultbutton="ucLogin$btnSubmit">

(Naming: The ucLogin part before the dollar sign needs to be the ID of your login control, as declared further down in your page. The btnSubmit part needs to be the ID of the button as it's named in the login control's html)

Next, you need to wrap the declaration of your login control in a panel, and set it's DefaultButton property, as well:

<!-- Login Control - use a panel so we can set the default button -->
<asp:Panel runat="server" ID="loginControlPanel" DefaultButton="ucLogin$btnSubmit">                         
     <uc:Login runat="server" ID="ucLogin"/>                                                    
</asp:Panel>

That should do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM