Fork me on GitHub

Wednesday, June 10, 2009

Reminder to self: How to use ASP.NET AJAX PageMethods

posted by Lars Hundebøl # 1:45 p.m.

I keep forgetting how to use the ASP.NET AJAX PageMethods (.NET 3.5), so here is a short examples that gets me up to speed:

In Default.aspx.cs insert the following static method declared with the WebMethod attribute:

[WebMethod]
public static Person DoSomethingServerSide(
  string name, string email)
{
  Person p = new Person()
  {
    Name = name,
    Email = email
  };

  return p;
}

...and in the Default.aspx insert some JavaScript that leverage this PageMethod:

function DoSomethingClientSide()
{
  PageMethods.DoSomethingServerSide(
    "Test", "test@test.com", Callback);
}

function Callback(res)
{
  alert(res.Name + " " + res.Email);
}

And that's it... no wonder I keep forgetting how easy it is.

Gravatar of propellerhead

propellerhead

 
Oh yeah: Forgot to mention that an asp:scriptmanager tag also must be on the page (or master).
 

Leave a comment

Your name

Your e-mail (will not be displayed)†

†Your e-mail will never be displayed and only used on the site to display your gravatar (if you got one), and as a means to potentially get back to you, if I have any feedback or questions regarding your comment.

all posts