2

i'm trying to follow the suggestion here: Call ASP.NET function from JavaScript?

But it's not working for me. The page does post back. but my RaisePostBacKEvent never fires. I am doing this in a usercontrol and not a page:

public partial class MyTreatment : System.Web.UI.UserControl, IPostBackEventHandler

Anyone have any suggestions on how to get this working?

Thanks

Community
  • 1
  • 1
merk
  • 1,721
  • 5
  • 23
  • 39

2 Answers2

5

Are you specifying the ClientID of your control, as opposed to the ClientID of the page (as in the example from the other SO question you referenced)?

If not then that would explain why the page is posting back but not calling the RaisePostBack method in your control.

To reference the ClientID of your control, call the __doPostBack function like so:

__doPostBack("<%= yourControlID.ClientID %>", "an argument");

As a side note, if your control is the only control on the page then the __doPostBack function will not be created by ASP.NET unless you make a call to GetPostBackEventReference for your control.

You do not necessarily need to make use of the reference but you need to call the method so the page knows to generate the client side function.

You can call GetPostBackEventReference like so:

public class MyTreatment : UserControl, IPostBackEventHandler
{
    protected override void OnLoad(EventArgs e)
    {
        string postBackEventReference = Page.ClientScript.GetPostBackEventReference(this, string.Empty);

        base.OnLoad(e);
    }

    public void RaisePostBackEvent(string eventArgument)
    {

    }
} 

Hope this helps.

jdavies
  • 12,784
  • 3
  • 33
  • 33
  • i found another way of doing this using OnClientClick="return myJSFunction();" But i'll mark your reply as the answer even though i'm not sure if that was the issue i was having. Thanks – merk Sep 28 '11 at 04:42
2

It should work with using the user control instance ID's UniqueID property (I couldn't get this to work with ClientID, in my own personal experiences). Like so:

__doPostBack("<%= yourControlID.UniqueID %>", "arg");
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • 1
    I've experienced the same thing after migrating to .NET 4.0 - in the end I've found out that RaisePostBackEvent was never fired (control implements the IPostBackEventHandler interface) due to the wrong control ID - during control creation somewhere in Render I've added __doPostBack and in debug the ID seemed correct like "ctlContainer_grdDataGrd", but on the page it was "ctlContainer$grdDataGrd". After changing in code ClientID to UniqueID for generated JavaScript (for __doPostBack function params), all works like charm! – Ivan Jun 11 '14 at 12:13