gpt4 book ai didi

c# - ASP .NET Button 事件处理程序不会在第一次单击时触发,而是在 PostBack 后的第二次单击时触发

转载 作者:IT王子 更新时间:2023-10-29 04:01:53 27 4
gpt4 key购买 nike

背景:我正在自定义一个现有的 ASP .NET/C# 应用程序。它有自己的小“框架”和开发人员在扩展/定制其功能时要遵循的约定。我目前正在扩展它的一些管理功能,框架提供了一个契约(Contract)来强制实现 GetAdministrationInterface() 方法,该方法返回 System.Web.UI.Control .在托管 GUI 界面的页面的 Page_Load() 方法期间调用此方法。

问题:我的 GUI 中有三个按钮,每个按钮都分配了一个事件处理程序。我的管理 GUI 加载得非常好,但是单击任何按钮都没有按照我的预期进行。但是,当我第二次单击它们时,这些按钮起作用了。

我在每个事件处理程序方法的开头放置了断点并逐步执行我的代码。第一次点击时,没有触发任何事件处理程序。在第二次点击时,他们开火了。

有什么想法吗?

按钮定义示例(在 GetAdministrationInterface 中)

public override Control GetAdministrationInterface()
{
// more code...

Button btn = new Button();
btn.Text = "Click Me!";
btn.Click += new EventHandler(Btn_Click);

// more code...
}

事件处理程序方法定义示例

void Btn_Click(object sender, EventArgs e)
{
// Do Something
}

Page_Load 调用 GetAdministrationInterface

的方法
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsAsync)
{
List<AdministrationInterface> interfaces = <DATABASE CALL>;
foreach(AdministrationInteface ai in interfaces)
{
placeholderDiv.Controls.Add(ai.GetAdministrationInterface());
}
}
}

最佳答案

天啊!我知道这会是这么愚蠢的事情。当然,这完全是我的错以及我对 ASP .NET 知识的缺乏。

在进行了大量的谷歌搜索并最终因怀疑是运行自动脚本的机器人而被谷歌阻止后,我设法挤进了最后一次搜索并偶然发现了这个 article .已经快要放弃了,我尽我最大的努力阅读这篇文章,而不是一次跳过 10 行或寻找漂亮的图片。在标题为为动态创建的控件分配 ID 的部分中,我读到了这些神奇且最令人愉快的话:

If you view the source HTML before you click the not-working button and after you have clicked it, you will notice a small difference. The buttons have different HTML IDs before and after the post-back. I got ctl04 and ctl05 before the post-back and ctl02 and ctl03 after the post-back.

ASP.NET button recognizes events by checking for a value for its ID in the Request.Form collection. (In truth it happens differently and controls do not check Request.Form collection by themselves. Page passes post data to controls by their IDs and to controls that are registered to be notified about post data). ASP.NET does not fire the Click event, because the button's ID has changed between the post-backs. The button you have clicked and the button you see after are different buttons for ASP.NET.

果然,当我第一次查看 HTML 时,我的按钮有 ID ctl04$ctl36。单击按钮后,我的按钮的 ID 为 ctl04$ctl33

原来如此!我所要做的就是在按钮上设置 ID,然后就可以了!现在正在调用我的事件处理程序!

示例解决方案:

public override Control GetAdministrationInterface()
{
// more code...

Button btn = new Button();
btn.Text = "Click Me!";
// !!THE BANE OF MY EXISTENCE!!
btn.ID = "The_Bane_of_My_Existence";
// !!THE BANE OF MY EXISTENCE!!
btn.Click += new EventHandler(Btn_Click);

// more code...
}

度过两天的好方法......

关于c# - ASP .NET Button 事件处理程序不会在第一次单击时触发,而是在 PostBack 后的第二次单击时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2765815/

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