[英]ASP.NET Call Another Element's DoPostBack Function
我有一個ASP.NET控件,該控件具有在元素上嵌入式呈現的onclick事件處理程序。 我想調用該函數並使它引發目標控件的服務器端事件處理程序。
<asp:CheckBox ID="Foo"
runat="server"
AutoPostBack="true"
Text="Foo" />
<a href="#"
onclick="javascript:setTimeout('__doPostBack(\'Foo\',\'\')', 0)">Test
</a>
我創建了復選框,在字段上查看了呈現的函數,然后將其復制到錨元素上的onclick中。
錨點將引發回發,但未引發該復選框的事件處理程序。
protected override void OnLoad(EventArgs e)
{
// fires for checkbox
// fires for anchor (the anchor does cause a postback)
}
void Foo_CheckedChanged(object sender, EventArgs e)
{
// fires for checkbox
// does not fire for anchor
}
protected override void OnInit(EventArgs e)
{
this.Foo.CheckedChanged += new EventHandler(Foo_CheckedChanged);
}
是否有可能做到這一點?
不要嘗試手動確定JavaScript對於回發應該是什么樣子。 為任務使用正確的API ...在這種情況下,這正是GetPostBackEventReference的目的。
myControl.Attributes.Add("onclick", "javascript:" + ClientScript.GetPostBackEventReference(targetControl));
為什么不將標簽轉換為asp:linkbutton,然后為兩者使用一個處理程序
protected override void OnInit(EventArgs e)
{
this.Foo.CheckedChanged += new EventHandler(Foo_CheckedChanged);
this.Bar.Click+= new EventHandler(Foo_CheckedChanged);
}
您的客戶端ID復選框現在可能是“ Foo”。
使用以下命令確保您為元素使用正確的ClientID
<a href="#"
onclick="javascript:setTimeout('__doPostBack(\'<%= Foo.ClientID %> \',\'\')', 0)">Test
</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.