单击按钮时,OnClick不会在UserControl中触发

时间:2015-04-25 16:38:10

标签: c# asp.net button user-controls

我有一个母版页。在母版页中,我有一个页脚的UserControl。在页脚中,我有一个没有触发OnClick的按钮。在调试过程中,我看到OnClick调用的函数btnSignup_Click没有被命中。我似乎无法弄清楚代码中的错误在哪里 另外我想要注意验证功能是否正常工作。

master.master

<%@ Master Language="C#" AutoEventWireup="true" Inherits="master" Codebehind="master.master.cs" %>
<%@ Register TagPrefix="xyz" TagName="Footer" Src="~/controls/footer.ascx" %>


<xyz:Footer ID="Footer" runat="server" />

footer.ascx

<%@ Control Language="C#" AutoEventWireup="true" Inherits="footer" Codebehind="footer.ascx.cs"  %>

<div>
     <asp:TextBox ID="fName" runat="server"></asp:TextBox>
     <asp:RequiredFieldValidator ID="RequiredFieldValidatorfName"  ValidationGroup="validationSignup" Display="Static" ControlToValidate="fName" ErrorMessage="First Name required" runat="server"></asp:RequiredFieldValidator>
</div>

<div class="button">
    <asp:Button ID="btnSignup"  CommandName="Button" runat="server" ValidationGroup="validationSignup" Text="Signup"  HeaderText="Please fill in all required fields before continuing." OnClick="btnSignup_Click"/>
</div>

<div class="validationSummary">                 
    <asp:ValidationSummary ID="ValidationSummary"   ValidationGroup="validationSignup" runat="server"></asp:ValidationSummary>
</div>

footer.ascx.cs

public partial class templates_site_footer : BaseUserControl
{       
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSignup.Click += new EventHandler(btnSignup_Click);
    }
    protected void btnSignup_Click(object sender, EventArgs e)
    {       
        if (!Page.IsValid)
            return;

        // code to execute after button is clicked
    }
}

1 个答案:

答案 0 :(得分:0)

从Page_Load事件中删除btnSignup.Click += new EventHandler(btnSignup_Click);代码,您已经在.ASCX标记中将OnClick事件分配给按钮,而无需再次在btnSignup_Click中检查您的网页验证,您可以直接写按钮单击要执行的事件代码。

您的页脚用户控制代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    //btnSignup.Click += new EventHandler(btnSignup_Click);
}

protected void btnSignup_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
         // code to execute after button is clicked
    }
    else
    {
         // Your page does not validated.
    }
}