Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>PageMethods are static methods in the code behind decorated with the <code>[WebMethod]</code> and the <code>[ScriptMethod]</code> attributes (Actually the <code>[ScriptMethod]</code> attribute is not required if you are not using the jjavascript proxy generated by ASP.NET to invoke the PageMethod - see below in my answer for more information about calling the PageMethod). They can take an arbitrarily complex .NET objects as input and output. They use JSON as serialization mechanism. </p> <p>Let's take an example of a PageMethod defined in the codebehind of a WebForm:</p> <pre><code>[WebMethod] [ScriptMethod] public static User[] FindUsers(User criteria) { ... do some filtering on the criteria and return a User array with the results } </code></pre> <p>where the User class might look like this:</p> <pre><code>public class User { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> <p>On the client side you could invoke this PageMethod either using the built-in Microsoft AJAX framework which will automatically generate a typed javascript proxy to call the PageMethod:</p> <pre><code>var criteria = { FirstName: 'john', LastName: 'smith' }; PageMethods.FindUsers(criteria, function(users) { // success =&gt; you could directly use the "users" variable here // that will represent the result returned by your page method // for example for (var i = 0; i &lt; users.length; i++) { alert(users[i].FirstName); } }, function() { // failure }); </code></pre> <p>In order for this proxy to be generated the PageMethod must be decorated with the <code>[ScriptMethod]</code> attribute.</p> <p>As an alternative to using the autogenerated javascript proxy you could also use jQuery to invoke a PageMethod:</p> <pre><code>var criteria = { FirstName: 'john', LastName: 'smith' }; $.ajax({ type: 'POST', url: 'PageName.aspx/FindUsers', data: JSON.stringify(criteria: criteria), contentType: 'application/json; charset=utf-8', success: function(result) { // success =&gt; you need to use "result.d" to access the actual object // that was returned by the PageMethod var users = result.d; for (var i = 0; i &lt; users.length; i++) { alert(users[i].FirstName); } }, error: function() { // failure } }); </code></pre> <p>In case of directly invoking the PageMethod with javascript without using the proxy you don't need to decorate the PageMethod with the <code>[ScriptMethod]</code> attribute since we don't care about this proxy as we are not using it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload