从代码隐藏添加OnClick到按钮

tec*_*ora 2 c# asp.net onclick button

我试图从后面的代码中添加一个OnClick属性到一个按钮.取决于Attending元素是否为0,将确定添加哪个OnClick属性.当我单击带有下面代码的按钮时,我收到以下错误:

"Microsoft JScript运行时错误:Sys.WebForms.PageRequestManagerServerErrorException:无效的回发或回调参数.使用配置或页面中的<%@ Page EnableEventValidation ="true"%>启用事件验证.出于安全考虑,此功能验证参数回发或回调事件源自最初呈现它们的服务器控件.如果数据有效且预期,请使用ClientScriptManager.RegisterForEventValidation方法注册回发或回调数据以进行验证."

我究竟做错了什么?

ASPX

<%@ Page Title="" Language="C#" EnableEventValidation="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="test.CommunityEvents.Default" %>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:DataList ID="DataList1" RepeatColumns="1" CellPadding="5" OnItemDataBound="Dl1_ItemDataBound"
            runat="server">
            <ItemTemplate>
                   <div id="Attendingbox" runat="server">
                       <asp:Label ID="AttendingorNot" runat="server"></asp:Label>
                    </div>
                    <br />
                    <asp:Button ID="SignupButton" runat="server" Text="" />
            </ItemTemplate>
        </asp:DataList>
    </ContentTemplate>
</asp:UpdatePanel>
Run Code Online (Sandbox Code Playgroud)

代码背后

protected void Dl1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            .....//removed other code to save space

            Button SignupButton = (Button)e.Item.FindControl("SignupButton");
            if (Attending == 0)
            {
                AttendingorNot.Text = "You are not attending";
                AttendingorNot.Attributes.Add("class", "alert");
                SignupButton.Text = "Attend";
                SignupButton.Attributes.Add("class", "btn btn-large btn-success");
                SignupButton.Click += new EventHandler(Submit_Add);
            }
            else
            {
                AttendingorNot.Text = "You are attending!";
                AttendingorNot.Attributes.Add("class", "alert alert-success");
                SignupButton.Text = "Remove";
                SignupButton.Attributes.Add("class", "btn btn-large btn-danger");
                SignupButton.Click += new EventHandler(Submit_Remove);
            }
        }
    }
    private void Submit_Remove(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?msg=work");
    }
    private void Submit_Add(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?msg=gone");
    }
Run Code Online (Sandbox Code Playgroud)

小智 8

使用以下代码

Button1.Attributes.Add("OnClick","btn_Click");
Run Code Online (Sandbox Code Playgroud)

要么

Button1.Click += new EventHandler(btn_Click);
Run Code Online (Sandbox Code Playgroud)

这是按钮单击方法

protected void btn_Click(object sender, EventArgs e)
{
   do anything...        
}
Run Code Online (Sandbox Code Playgroud)