.NET AJAX Calls to ASMX or ASPX or ASHX?

The ScriptService stuff in my opinion is a hidden gem in asp.net. Calls to the script service do not passback form data + viewstate, they are lean, fast JSON payloads.

Heres the best part, ASP.NET3.5’s scriptmanager can do most of the work for you regarding generating a JS method for you to call and also setting up any JS classes needed.

A simple example for fetching details for a “Person”, assuming Person is a C# class.

In PersonService.asmx:

namespace MyProj.Services {
  [System.Web.Script.Services.ScriptService]
  [System.Web.Script.Services.GenerateScriptType(typeof(Person))] 
  public class PersonService : System.Web.Services.WebService
  {
    [WebMethod, ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public Person GetPersonDetails(int id)
    { 
       /* return Logic here */
    }
  }
}

In DetailsPage.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
 <Services>
  <asp:ServiceReference Path="~/Services/PersonService.asmx" />
 </Services>
</asp:ScriptManager>

By using a setup like this, you won’t even need the help of JQuery to call the service and get back a JS version of your C# Person class, .net does that all for you.
An example of using this service from JS would be:

MyProj.Services.PersonService.GetPersonDetails(id, _onDetailsCallbackSuccess, _requestFailed, null);

_onDetailsCallbackSuccess: function(result, userContext, methodName) {
 //all persons properties are now intact and available
 document.getElementById('txtFirstname').value = result.Firtname;
}

Anyway, it would be more then worth looking into the ASP.NET Ajax ScriptService stuff. Even if you decide not to use it this time it’s a pretty wicked feature.

Links

  • Looks like a nice basic example of using a scriptservice: http://www.jankoatwarpspeed.com/post/2008/05/14/asp-net-ajax-basics-calling-scriptservices-using-javascript.aspx
  • ASP.NET Ajax Extenders, the next logical steps to integrating Ajax into your controls. http://weblogs.asp.net/scottgu/archive/2007/08/19/using-asp-net-ajax-control-extenders-in-vs-2008.aspx

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)