Geekery

As one of the eggheads here at Sumac I’ll be putting up some technical posts from time to time. Hopefully these will prove useful to other developers.

A while back I had to jump through the hoops of getting some Ajax going using Json on an ASP.NET 2.0 web service. It was for a reality version of PredictorPro.

So for today’s recipe our ingredients are:

  • ASP.NET 2.0 web site with web service
    We’re using a web site with the service inside. This should work for a similar web app or stand alone web service app.
  • ASP.NET Ajax Extensions 1.0
  • jQuery (currently 1.3.2)
  • Ajax
  • Json

The key areas to cover are:

  • Setting up the web service to handle Json
  • Making the Ajax call in jQuery

Setting up the web service

1. If you haven’t already got it, you’ll need the ASP.NET Ajax Extensions 1.0. They can be downloaded from the link above. Once installed, add a reference to System.Web.Extensions.

2. In the web.config ensure you have:

<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>

3. To handle the Json, in the web.config you’ll also need:

<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>
</system.web>

4. Your web service class should look something like (important part is the ScriptService reference):

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld(ByVal ArgumentName As String) As String
Return "Hello World " & ArgumentName
End Function
End Class

Making the Ajax call with jQuery

As simple as:

$.ajax({
type: 'POST',
url: '/WebService.asmx/HelloWorld',
data: '{ArgumentName:"ArgumentValue"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Celebrate
}
});

Best of luck and drop any questions or comments below.