Phi*_*nin 2 .net c# asp.net event-handling
我有ASPX网页,上面有一个按钮.用户单击此按钮后,将请求提交给服务器并执行按钮单击事件处理程序.
我有一些逻辑必须驻留在Page.Load上,但是这个逻辑取决于是否通过按钮点击提交了请求.基于页面生命周期事件处理程序在页面加载后执行.
问题:如何在页面加载中找出页面加载后要执行的事件处理程序?
@ akton的答案可能就是你应该做的,但是如果你想要退出预订并确定在生命周期的早期发生什么导致回发,你可以查询回发数据以确定点击的内容.但是,这不会为您提供在事件处理期间将执行的实际函数/处理程序.
首先,如果除了Button/ ImageButton引起回发之外的其他内容,控件的ID将在__EVENTTARGET.如果a Button引起了回发,那么ASP.NET会有一些"可爱的":它会忽略所有其他按钮,这样只有单击的按钮才会显示在表单上.An 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;
}
Run Code Online (Sandbox Code Playgroud)
所有这一切,如果您可以重构您的控件/页面以延迟执行,如果您使用@akton建议的范例,您的代码将更清晰/更强大.
| 归档时间: |
|
| 查看次数: |
5873 次 |
| 最近记录: |