gpt4 book ai didi

c# - 在 Page.Load 期间确定是否要处理 Button 单击事件

转载 作者:行者123 更新时间:2023-11-30 19:18:34 25 4
gpt4 key购买 nike

我有一个 ASPX 网页,上面有一个按钮。一旦用户点击这个按钮,请求被提交到服务器并执行按钮点击事件处理程序。

我有一些必须驻留在 Page.Load 上的逻辑,但此逻辑取决于是否通过单击按钮提交了请求。基于page life cycle事件处理程序在页面加载后执行。

问题:如何在页面加载中找出页面加载后要执行的事件处理程序?

最佳答案

@akton 的回答可能是你应该做的,但如果你想取消预订并在生命周期的早期确定导致回发的原因,你可以查询回发数据以确定点击了什么。但是,这不会告诉您在事件处理期间将执行哪些实际函数/处理程序。

首先,如果不是 Button/ImageButton 导致回发,控件的 ID 将在 __EVENTTARGET 中。如果 Button 导致回发,ASP.NET 会做一些“可爱”的事情:它会忽略所有其他按钮,因此只有单击的按钮会显示在表单上。 ImageButton 有点不同,因为它会发送坐标。您可以包括的效用函数:

public static Control GetPostBackControl(Page page)
{
Control postbackControlInstance = null;

string postbackControlName = page.Request.Params.Get("__EVENTTARGET");
if (postbackControlName != null && postbackControlName != string.Empty)
{
postbackControlInstance = page.FindControl(postbackControlName);
}
else
{
// handle the Button control postbacks
for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
return postbackControlInstance;
}
}
}
// handle the ImageButton postbacks
if (postbackControlInstance == null)
{
for (int i = 0; i < page.Request.Form.Count; i++)
{
if ( (page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length-2) );
return postbackControlInstance;
}
}
}
return postbackControlInstance;
}

综上所述,如果您可以重构您的控件/页面以延迟执行,如果您使用@akton 建议的范例,您的代码将更加清晰/更加健壮。

关于c# - 在 Page.Load 期间确定是否要处理 Button 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272961/

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