正在确定导致PostBack的控件
本文关键字:PostBack 控件 | 更新日期: 2023-09-27 18:28:07
我有这个aspx:
<asp:ImageButton ID="check" runat="server" ImageUrl="../img/process.png" OnClick="check_Click" CausesValidation="false" UseSubmitBehavior="false"/>
现在在Page_Load
中,我想确定是由check
引起的PostBack
还是否,所以我用这个代码遵循了这个问题的方法:
if(FindControl(Page.Request.Params.Get("__EVENTTARGET"))!=check)//if not caused by "check"
//do something
但CCD_ 4为空。(我在UpdatePanel
中使用我的ImageButton
)
我怎样才能达到我的目标?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
return;
Control control = null;
string controlName = Page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = Page.FindControl(controlName);
}
else
{
string controlId;
Control foundControl;
foreach (string ctl in Page.Request.Form)
{
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 Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
Label1.Text = control.ID; // label1 must be in UpdatePanel
}
试试这个:
Control ctrl = null;
string target = Page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(target))
ctrl = page.FindControl(target);
if(ctrl == check){
//check is the control that caused postback
}
**更新**
好的,原来ImageButtons的功能有点不同。使用此标记:
<asp:ImageButton onClientClick="setTarget(this.id)" ID="check" runat="server" ImageUrl="../img/process.png" OnClick="check_Click" CausesValidation="false" UseSubmitBehavior="false"/>
<asp:HiddenField ID="targetId" runat="server" />
现在创建一个javascript函数,它将用启动PostBack的字段ID填充我们的隐藏字段:
function SetSource(id)
{
var targetId=
document.getElementById("<%=targetId.ClientID%>");
targetId.value = id;
}
最后,我们在我们的PostBack中查看:
Control ctrl = null;
if (Request.Form[targetId.UniqueID] != null &&
Request.Form[targetId.UniqueID] != string.Empty)
{
ctrl = Page.FindControl(Request.Form[targetId.UniqueID]);
}
if(ctrl == check){
//check is the control that caused postback
}
参考:http://www.aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
由于这是一个更新面板,请尝试通过ScriptManager
获取值,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
var updatePanelControlIdThatCausedPostBack = String.Empty;
var scriptManager = ScriptManager.GetCurrent(Page);
if (scriptManager != null)
{
var smUniqueId = scriptManager.UniqueID;
var smFieldValue = Request.Form[smUniqueId];
if (!String.IsNullOrEmpty(smFieldValue) && smFieldValue.Contains("|"))
{
updatePanelControlIdThatCausedPostBack = smFieldValue.Split('|')[1];
}
}
if (!String.IsNullOrEmpty(updatePanelControlIdThatCausedPostBack))
{
// Do something with control ID value that caused UpdatePanel postback here
}
}
如果控件导致PostBack
,则其ID
在请求集合Form.Request[controlID]
中将是非null
。
在Image
的情况下,请求集合中有两个项目,一个用于x坐标,另一个用于y坐标,用于鼠标在图像中的确切点击位置。
那么做:
if(Form.Request["Img1.x"] != null)