sfd8hw
Last Updated: February 25, 2016
·
1.377K
· dieseltravis
Tenet travis

Ajaxify a function in ASP.Net

It's extremely easy to add a web service to any Asp.Net web forms page. Just make sure the function is static in C# or Shared in VB, and add the WebMethod and ScriptMethod to the function's signature. C#:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string GetSomeObjects(string id)
{
    return "Do stuff here with " + id;
}

VB:

<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetSomeObjects(ByVal id As String) As String
    Return "Do stuff here with " & id
End Function

Then you can call these functions in javascript with jQuery:

$.ajax({
  type: "POST",
  url: "SomePage.aspx/GetSomeObjects",
  //    ^Page name    ^public static name
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: "{'id': '" + someId.replace(/'/g, "\\'") + "'}",
  //       ^Param    ^value, escape apostrophes
  success: function(json) {
    // do something with JSON data, if necessary
  }
});

Fork the gist: https://gist.github.com/773291

(PS: Sorry about the formatting in that jQuery block, I can't seem to get it to look right!)

Say Thanks
Respond

1 Response
Add your response

3709
D940dd93751cea6229c4b9b2098b7f39

weird!

over 1 year ago ·