Client and Server side interaction using VS 2008 ASP.NET AJAX

logo Developer

Overview

In our previous article “invoking server side code using AJAX” (http://www.viawindowslive.com/Articles/VirtualEarth/InvokingserversidecodeusingAJAX.aspx), we investigated how to send a request from the client side to the server side using the AJAX xmlhttprequest object.  Visual Studio 2008 has greatly simplified process so that now you don’t need to setup and manage xmlhttprequest calls, or even worry about serialization/de-serialization of objects (using third party libraries).  All of this is wrapped up nicely by the use of web services and the ASP.NET AJAX script manager.

 To start, create a standard ASP.NET Web Application called WebApplication1.  Next, add a web service to your project.

ajax1 Developer

Uncomment this auto-generated attribute in the web service:

//[System.Web.Script.Services.ScriptService]

Next, switch to your Default.aspx file and add a reference to the script manager by drag and dropping from the toolbox onto your page.

ajax3 Developer

An alternative is to add this code in (must be encased in a <forms runat=”server”> tag):

     <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
    </asp:ScriptManager>

Next, reference your web service within the script manager:

    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        <Services>
            <asp:ServiceReference Path=”~/WebService1.asmx” />
        </Services>
    </asp:ScriptManager>       

 Using the Namespace in your web service, you can now invoke a web method using Javascript from default.aspx.  For example:

function callWebService()

{

webApplication1.webService1.HelloWorld(callbackFunction);

}

function callbackFunction(response)

{

alert(response);
}

The last parameter specified in your web service call will automatically be a pointer to your callback function.  In this case, the HelloWorld method generated by default using Visual Studio 2008 did not accept any parameters so ‘callbackFunction’ was automatically chosen as the function pointer.  “Hello World” will be printed on the screen.

The real power is that ASP.NET AJAX automatically serializes/de-serializes any object returned through the web service.  Here is an example web method that returns a generic list of strings.

         [WebMethod]
        public List<String> GenericListResponse()
        {
            List<String> response = new List<String>();
            response.Add(“Hello”);
            response.Add(“World”);
            return response;
        }

On the front end this will be returned as an array (JavaScript equivalent) with “Hello” at index 0 and “World” at index 1.  That’s basically all you need to understand how client/server side communication works in Visual Studio 2008 and there’s sample code we’ve discussed as a reference below:

Sample code:

Default.aspx

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”WebApplication1._Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title>
    <script>
        function callWebService()
        {
            WebApplication1.WebService1.HelloWorld(callbackFunction);
        }
        function callbackFunction(response)
        {
            alert(response);
        }
    </script>   
</head>
<body onload=”callWebService()”>
    <form id=”form1″ runat=”server”>
    <div>
   
    </div>
    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        <Services>
            <asp:ServiceReference Path=”~/WebService1.asmx” />
        </Services>
        </asp:ScriptManager>       
    </form>
</body>
</html>

WebService1.asmx

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;

namespace WebApplication1
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = “http://tempuri.org/“)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
     [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return “Hello World”;
        }

    }
}