Call a WebService with ASP.Net Ajax

 In this post I’m going to show you a very simple example where I will from a Web
Form call a Web Service without reloading the page.When we will use ASP.Net Ajax on
our pages we need to add the <asp:ScriptManager> element.
The ScriptManager will automatically add the references to the required JavaScript
files that provide Atlas functionality. So it’s required on every page where we will
use the ASP.Net Ajax features.
When we want to add a reference to our WebService we use the Service child element
of the ScriptManager:

<asp:ScriptManager ID="ScriptManager1" runat="server">
          <asp:ServiceReference Path="~/WebService.asmx" />
The code above will add a reference to “MyWebService.asmx”. Let’s take a look at the MyWebService:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

/// Summary description for WebService
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService

   Public WebService()

     //Uncomment the following line if using designed components

 public  string MyMethod(string value)
     return value;

The addition of the [ScriptService] Attribute opens up this web service for use with AJAX.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientWebService.aspx.cs"
   Inherits="ClientWebService" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head id="Head1" runat="server">
   <title>Untitled Page</title>
   <form id="form1" runat="server">
   <asp:ScriptManager ID="ScriptManager1" runat="server">
           <asp:ServiceReference Path="~/WebService.asmx" />
       <input type="button" onclick="CallMyWebService();" id="myButton" value="Call MyWebService" />

   <script type="text/javascript">
function CallMyWebService()

     WebService.MyMethod("My Value", OnRequestComplete);
function OnRequestComplete(result)




Post a Comment


Close Menu