asp.net - how - calling an ascx page method using jquery




how to call ascx page from jquery (6)

I know that I can call a page method with jquery using the following syntax

$.ajax({
  type: "POST",
  url: "Default.aspx/GetDate",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Replace the div's content with the page method's return.
    $("#Result").text(msg.d);
  }
});

This works for aspx pages but is it possible with ascx pages? (web controls)

I've been trying it for about half an hour and since I can't get it to work I'm wondering if it's even possible.

Note: Just to be clear, when I try to call the ascx page I am updating the url in jquery :)




I don't think it's possible by requesting the ascx file directly--i.e. supplying "MyControl.ascx" as the url parameter to $.ajax(..). The ascx file isn't exposed directly by the web server.

You can, I believe, supply the url of the aspx page containing the user control--i.e. if an instance of MyControl.ascx lives on MyPage.aspx you would have to supply "MyPage.aspx" as the url parameter. It sounds like that might defeat the purpose for what you're trying to accomplish though.

EDIT: What Clyde said below seems like a good idea. I'm doing something similar myself by including the ascx control on a page whose job is more or less just to host it for access from client-side script.


I would create a Generic Handler (.ashx) which Loads the control and writes its rendered HTML to the Response.


What about creating the method on the .aspx page that does what it needs to with the information from the control? I know people go back and fourth on what controls are supposed to contain or not contain, but if the control only contains properties and objects, I would think having the function in the .aspx page could work for you. Obviously there would be many trade-offs.


You can write method GetDate() in Default.aspx or an other aspx file AND YOU CAN CALL THAT METHOD FROM .ASCX FILE.

Ex:

In UserControl.ascx:

$.ajax({
 type: "POST",
 url: "Default.aspx/GetDate",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg) {
 // Replace the div's content with the page method's return.
 $("#Result").text(msg.d);
}

});

In Default.aspx.cs:

Public void GetDate() //Public static void { //your code here }





pagemethods