Skip to main content

Consuming Web Services With ASP.NET AJAX

<%@ Page Language="C#" %>

<!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>SingingEels - Consuming Web Services with ASP.NET AJAX Demo</title>

   <script type="text/javascript">
function findVendor() {
   var zipCode = $get("ZipCode").value;

   VendorLocator.GetNearestDealer(function(result) {
       // Assign the Distance
       $get("distance").innerHTML = result.Distance;

       // Assign the Name
       $get("name").innerHTML = result.Name;

       // Assign the Phone Number
       $get("phoneNumber").innerHTML = result.PhoneNumber;

       // Make the dealer results visible
       $get("dealerResults").style.display = "";
   });
}

   </script>

</head>
<body>
   <form runat="server">
       <asp:ScriptManager ID="ScriptManager" runat="server">
           <Services>
               <asp:ServiceReference Path="~/VendorLocator.asmx" />
           </Services>
       </asp:ScriptManager>
       <h1>
           Search Page</h1>
       <p>
           Enter your zip code below to find the closest product vendor.</p>
       <fieldset>
           <label>
               Zip Code<input type="text" id="ZipCode" /></label>
           <button onclick="findVendor();">
               Search
           </button>
       </fieldset>
       <dl id="dealerResults" style="display: none;">
           <dt>Distance:</dt>
           <dd id="distance" />
           <dt>Name:</dt>
           <dd id="name" />
           <dt>Phone:</dt>
           <dd id="phoneNumber" />
       </dl>
   </form>
</body>
</html>
using System.Web.Script.Services;
using System.Web.Services;

[ScriptService]
public class VendorLocator : WebService
{
    [WebMethod, ScriptMethod]
    public SearchResult GetNearestDealer()
    {
        // We are intentionally returning a hard coded result for this example.
        return new SearchResult(20, "Bob's Widget Store", "(555) 567-8901");
    }
}

// This is our "SearchResult" class which will automatically be JSON serialized
// by ASP.NET AJAX and passed into JavaScript as a parameter.
public class SearchResult
{
    public SearchResult()
    {
    }

    public SearchResult(int distance, string name, string phoneNumber)
    {
        this.distance = distance;

        this.name = name;

        this.phoneNumber = phoneNumber;
    }

    private int distance;
    public int Distance
    {
        get { return this.distance; }
        set { this.distance = value; }
    }

    private string name;
    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }

    private string phoneNumber;
    public string PhoneNumber
    {
        get { return this.phoneNumber; }
        set { this.phoneNumber = value; }
    }
}

Comments

Popular posts from this blog