First go at AJAX and ASP.Net

There are two way to do dynamic page update without a post-back in ASP.Net. There is the much vaunted UpdatePanel with all its overhead. No , it works just fine within your own application. Though make ultimate use it would require several UpdatePanels on a page to make a fantastic application. The other way is to use the AJAX calls within jQuery to either your own webservice or a 3rd party webservice. Certainly when building your own application the UpdatePanel is the way to go. But AJAX can still be used though you need to take care not to page refresh when using it. Its certainly a useful option when dealing with 3rd party webservices to display information. So how is this done?

AJAX in jQuery

There are three main components to be used. jQuery, JSON and a webservice. For this example I’ll write the webservice in ASP.Net. On your webpage you’ll be having code similar to this

$.ajax({type: "POST",
                url: "/WebServices/SearchService.asmx/GetCustomerDetails",
                // Pass the "Count" parameter, via JSON object.
                data: "{ 'custID': " + custID + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var data = msg.d;

                    ... do stuff here ...
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus + " -- " + jqXHR.responseText);
                }});

Let’s break this down a bit.

  • type: This is either POST or GET. I prefer to use POST
  • url: Microsoft webservice files end with asmx and at the end you have the function that is being called
  • data: The JSON data string. Note that only simple data can be passed through. You can’t pass a structure through in this method.
  • contentType: this does seem important and the MS webservice will not work without it
  • success: When the AJAX returns without any errors this function will be invoked. And obviously the error will be called if an error occurs.

Inside the success function you’ll notice the following code:

var data = msg.d;

This is because the Microsoft webservice JSON code wraps the result with a ‘d’ element eg:

 {'d': { 'val1': 34, 'val2': 'so on..' }}

For more information on JSON go to JSON.org for a clear and simple explanation.

Now on to the web service.

.Net Webservice

I’ll now give a small sample of how to code the webservice in VB.Net. I’m sure you C# lads can translate easily enough.

In Visual Studio you will go to the ‘Add New Item…‘ menu item and select Web Service (asmx). Name it appropriately and click Add. Two files will get added, a .asmx and a .asmx.vb file. Ignore the .asmx file as it contains only the line

<%@ WebService Language="vb" CodeBehind="SearchService.asmx.vb" Class="MyProj.SearchService" %>

But when you open the .vb file you should see something similar to

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Script.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://msl.zolasystems.co.uk")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class SearchService
Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As searchResults
        Dim tmpResults As New searchResults
        tmpResults.nPage = "2"
        tmpResults.nValid = 0

        Return tmpResults
        'Return "Hello World"
    End Function
End Class

Now we’ll just add in our little bit of code after the default “Hello World” code:


Class clsCustomerDetails
     CustomerID As Integer
     CustomerName As String
     Address1 As String
     Address2 As String
     Address3 As String
     Address4 As String
     Address5 As String
     PostCode As String
     Telephone As String
     Mobile As String
     EMail As String
End Class

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetCustomerDetails(ByVal custID As Integer) As clsCustomerDetails
     Dim dt As DataTable
     Dim oReturnResult As New clsCustomerDetails
     Dim oCust As New clsCustomers
     dt = oCust.GetCustomerDetails(custID)
     'fill the result with the details
     Dim oDtRow As DataRow = dt(0)
     With oReturnResult
         ..fill the result in as you would..
     End With
     Return oReturnResult
End Function

And its just that simple. You let .Net take care of the unserialize and serialise to/from JSON. You notice that I don’t add the ‘d’ element in. That is done by the MS JSON serializer.

Conclusion

You can see just how simple using AJAX with jQuery and ASP.Net. I hope this helps you understand how to hook up jQuery to MS Webmethods. For those projects where the client is not (or does not want to) uses the ASP.Net script methods this technique is useful, and works!

Which often the most important thing eh?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.