在回发时,如何在Page_Init事件中检查导致回发的控件。
protected void Page_Init(object sender, EventArgs e)
{
//need to check here which control cause postback?
}谢谢
发布于 2010-08-18 15:14:37
我看到已经有一些很好的建议和方法来建议如何让帖子重新获得控制权。但是,我发现了另一个网页(Mahesh blog),其中包含一个检索回发控件ID的方法。
我将在这里发布它,并进行一些修改,包括使其成为一个扩展类。希望它能以这种方式更有用。
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}更新(2016-07-22):针对Button和ImageButton的类型检查已更改为查找IButtonControl,以允许识别来自第三方控件的回发。
发布于 2010-07-05 01:25:24
下面的代码可能会帮你解决这个问题(摘自Ryan Farley's blog)
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}发布于 2010-07-05 01:20:05
可以直接在表单参数中使用,或者
string controlName = this.Request.Params.Get("__EVENTTARGET");编辑:检查控件是否导致回发(手动):
// input Image with name="imageName"
if (this.Request["imageName"+".x"] != null) ...;//caused postBack
// Other input with name="name"
if (this.Request["name"] != null) ...;//caused postBack您还可以使用上面的代码遍历所有控件,并检查其中是否有一个控件导致了postBack。
https://stackoverflow.com/questions/3175513
复制相似问题