asp.netajaxeventscustom-controlscustom-server-controls

Raise event on custom server control from ajax?


I have a custom server control which is added to many different asp.net pages (it generates a blueimp jquery file upload plugin).

How can I raise an event on that server control from javascript/ajax? Or from an http handler? I'd like to raise an OnFileUploaded event on that control after jquery file upload has posted with ajax some files to an HTTP handler?

EDIT - In addition to Dalorzo's answer:

I've used the code that @Dalorzo wrote. Then I had to postback to my control as the target like this:

myctrlPostBackEventReference = Page.ClientScript.GetPostBackEventReference(myCtrl, "");
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "initMyClientVariable", "var postBackEventReference=\"" + myctrlPostBackEventReference + "\";", true);

and in my javascript file I've added:

eval(postBackEventReference)

to execute it.

Then I still had a problem that I wanted to prevent full page render, so I used the same method, but I posted back to a 'dummy' updatepanel as the target. The update panel raised the event on my desired control (I've sent the desired control id as an __EVENTARGUMENT (the second parameter of GetPostBackEventReference) for the update panel to distinguish which event should actually be raised.


Solution

  • You need to implement IPostaBackEventHandler and/or IScriptControl something like:

    [ToolboxData("<{0}:ComboBox runat=server></{0}:ComboBox>")]
    public class ComboBox : DropDownList, IScriptControl, IPostBackEventHandler 
    {
    

    Here is how you use IPostBackEventHandler:

      // Defines the Change event. 
      public event EventHandler Change;
    
      //Invoke delegates event Change. 
      protected virtual void OnChange(EventArgs e) {
    
         if (Change != null) {
            Change(this, e);
         }   
      }
    
      // Implements IPostBackEventHandler that raises the change events. 
      public void RaisePostBackEvent(string eventArgument){
         OnChange(new EventArgs());
      }