Using jQuery AJAX to call an ASP.NET function in code control mode instead of page code

I have a user control that I create that uses some AJAX in jQuery.

I need to call a function in the code for my control, but every example I found on the Internet looks like this:

$("input").click(function() { $.ajax({ type: "POST", url: "Default.aspx/GetResult", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { //do something } }); }); 

This works fine if I have a method on the Default.aspx page. But I do not want a function to be there, I need a function in the control code of my control. How to change url property to call the correct function?

I tried:

 url: "GetResult" 

but it didn’t work.

+4
source share
2 answers

You cannot ... WebMethods must be in WebServices or Pages, they cannot be inside UserControls.

Think about it differently to see the problem a little clearer ... what is the URL for UserControl? Since there is no access to them, you cannot directly access the method. Could you try a different method, perhaps a proxy method on your page?

+5
source

The way to handle this is to have a web method on your page and then just pass the values ​​directly to the control method with the same signature in your control - there is no other way to do this.

In other words, the ALL page method makes a call to the usercontrol method, so it is very small. If you have the same signature for multiple child controls, you can pass a parameter to specify the way the page can be called / used.

EDIT: on request (a very simple example). You can find other examples when more complex types are passed on the server side. for example, see my answer here: jquery.ajax async postback in C # UserControl

Example: Page method: pay attention to the "static" part.

 [WebMethod] public static string GetServerTimeString() { return MyNamespace.UserControls.Menu.ucHelloWorld(); } 

Custom Management Method:

 public static string ucHelloWorld() { return "howdy from myUserControl.cs at: " + DateTime.Now.ToString(); } 

Ajax client via jquery:

 $(document).ready(function() { /***************************************/ function testLoadTime(jdata) { $("#timeResult").text(jdata); }; $("#testTimeServerButton").click(function() { //alert("beep"); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: "{}", dataFilter: function(data) { var msg; if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') msg = JSON.parse(data); else msg = eval('(' + data + ')'); if (msg.hasOwnProperty('d')) return msg.d; else return msg; }, url: "MyPage.aspx/GetServerTimeString", success: function(msg) { testLoadTime(msg); } }); }); }); 

Note: dataFilter: function (data) ... part of ajax is that it works with asp.net ajax 2.0 and 3.5 without changing the client code.

+7
source

All Articles