Last Updated: February 25, 2016
·
2.606K
· dieseltravis

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!)

1 Response
Add your response

weird!

over 1 year ago ·