2

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.

I've seen the following articles;

The thing I don't get is how to do a postback to a specific method in either the code behind or another class.

I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?

Something along the lines of; $.post("class and action", ( param:value}......

Any thoughts, code etc???

Community
  • 1
  • 1
griegs
  • 22,624
  • 33
  • 128
  • 205

1 Answers1

4

It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.

Simply declare a method like this:

 [WebMethod]
  public static string GetDate()
  {
    return DateTime.Now.ToString();
  }

This is all you need in jQuery:

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg, status, xhr) {
    // Do something interesting here.
  }
});

Caveats:

  1. WebMethod must be on a static method
  2. Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
  3. msg is the response, the return result from your method is in the property msg.d
drzaus
  • 24,171
  • 16
  • 142
  • 201
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • Dang! Blocked by our company internet filter which blocks most useful development sites. Will check from home tonight thank you @TheVillageIdiot. Great name btw. – griegs Oct 12 '09 at 04:10