开发者

ASP.NET Call Another Element's DoPostBack Function

开发者 https://www.devze.com 2022-12-27 09:38 出处:网络
I have an ASP.NET control that has an onclick event ha开发者_开发问答ndler rendered inline on the element.I would like to call that function and have it raise the target control\'s server side event h

I have an ASP.NET control that has an onclick event ha开发者_开发问答ndler rendered inline on the element. I would like to call that function and have it raise the target control's server side event handler.

<asp:CheckBox ID="Foo" 
    runat="server" 
    AutoPostBack="true" 
    Text="Foo" />

<a href="#" 
    onclick="javascript:setTimeout('__doPostBack(\'Foo\',\'\')', 0)">Test
</a>

I created the checkbox, looked at the rendered function on the field, and then copied that into the onclick on the anchor element.

The anchor will raise a postback, but the event handler for the check box is not raised.

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);
}

Is it possible to do this?


Don't try to manually determine what the javascript should look like for a postback. Use the proper API for the task... in this case, this is exactly what GetPostBackEventReference is for.

myControl.Attributes.Add("onclick", "javascript:" + ClientScript.GetPostBackEventReference(targetControl));


Why not convert the tag to an asp:linkbutton and then have the one handler for both

protected override void OnInit(EventArgs e)
{
    this.Foo.CheckedChanged += new EventHandler(Foo_CheckedChanged);
    this.Bar.Click+= new EventHandler(Foo_CheckedChanged);
}


The client ID of you checkbox might now be "Foo".

Use the following to make sure you use the correct ClientID for your element

<a href="#" 
    onclick="javascript:setTimeout('__doPostBack(\'<%= Foo.ClientID %> \',\'\')', 0)">Test
</a>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号