gpt4 book ai didi

c# - 从代码隐藏中将 OnClick 添加到按钮

转载 作者:行者123 更新时间:2023-11-30 20:01:22 26 4
gpt4 key购买 nike

我正在尝试从后面的代码向按钮添加 OnClick 属性。根据 Attending 元素是否为 0 将决定添加哪个 OnClick 属性。当我单击带有以下代码的按钮时,出现以下错误:

"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."

我做错了什么?

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>

代码隐藏

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");
}

最佳答案

使用下面的代码

Button1.Attributes.Add("OnClick","btn_Click");

Button1.Click += new EventHandler(btn_Click);

这是按钮点击方法

protected void btn_Click(object sender, EventArgs e)
{
do anything...
}

关于c# - 从代码隐藏中将 OnClick 添加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19053694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com