To hook AjaxMethodCallback to a user or custom control:
Start by creating your control as usual and implement whatever features the control will have. The add your Callback methods that you want to expose to client callbacks and mark them up with [CallbackMethod] attribute as usual. Then add the OnInit() code to add the AjaxMethodCallback control that will handle these callback methods:
public class CustomControlUsingAjaxCallbacks : Control { protected override void OnInit(EventArgs e) { base.OnInit(e); AjaxMethodCallback callback = AjaxMethodCallback.CreateControlInstanceOnPage(this); // You can assign a custom id here which will reflect the generated proxy's name //callback.ID = "MyControl_Proxy"; } protected override void Render(HtmlTextWriter writer) { base.Render(writer); writer.Write("<div class='errordisplay'>dummy control placeholder</div>"); } [CallbackMethod] public string Add(int val1, int val2) { return val1 + val2; } }
That's all it takes on the server. The control takes care of the rest.
Using a Proxy:
function add() { MyControl_Callback.Add(parseInt($("#txtVal1").val()),parseInt($("#txtVal2").val()) function(result) { alert(result); }, function(error) { alert("Error: " + error.message); } ); }
You can also manually use xxx_xxx_GetProxy() if you decide you don't want to generate a proxy into the page (use GenerateClientProxy=false on the server control):
function add() { var myProxy = MyControl_Callback_GetProxy(); myProxy.callMethod("Add", [ parseInt($("#txtVal1").val()), parseInt($("#txtVal2").val()) ] function(result) { alert(result); }, function(error) { alert("Error: " + error.message); } ); }
To create an instance of the proxy that contains the properties configured by the server control you can use the <yourControlId>_Callback_GetProxy() method. This method is generated into the current HTML page so it'll be available to any script code in the same page or external .js files.
Then use the proxy instance and the callMethod() method to actually call the server. Pass the name of the method to call, along with the parameter in the proper type (int here) and an optional
This mechanism works both with custom and user controls using code.
this.MyCallbackProxy.TargetInstance = this;
Once AjaxMethodCallback enters into a callback the request will be ended after execution is complete or fails. The callback request is ended with Response.End().