Calling webservice with Ajax Javascript in asp.net

In this post, I will show you how to invoke the web services method using javascript. This is a very simple code and self-explanatory. Check out the following code snippet.


When we will use ASP.Net Ajax on our pages we need to add the element. The ScriptManager will automatically add the references to the required JavaScript files that provide

asp.net ajax 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:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallWebService.aspx.cs"  
Inherits="CallWebService" %>  
  
<!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 id="Head1" runat="server">  
  <title>Untitled Page</title>  
  
  <script language="javascript" type="text/javascript">  
      function CallMyWebService()  
      {  
          WebService.MyMethod("ASP dot net code book", OnRequestComplete);  
      }  
      function OnRequestComplete(result)  
      {  
          alert(result);  
      }  
  </script>  
  
</head>  
<body>  
  <form id="form1" runat="server">  
      <div>  
          <asp:ScriptManager ID="scriptManger1" runat="server">  
              <Services>  
                  <asp:ServiceReference Path="~/WebService.asmx" />  
              </Services>  
          </asp:ScriptManager>  
          <input type="button" onclick="CallMyWebService();" id="myButton" value="Call MyWebService" />  
      </div>  
  </form>  
</body>  
</html>  

CodeBehind

using System;  
using System.Web;  
using System.Collections;  
using System.Web.Services;  
using System.Web.Services.Protocols;  
  
  
/// <summary>  
/// Summary description for WebService  
/// </summary>  
[WebService(Namespace = "http://tempuri.org/")]  
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
[System.Web.Script.Services.ScriptService]  
public class WebService : System.Web.Services.WebService  
{  
  
   public WebService()  
   {  
  
       //Uncomment the following line if using designed components   
       //InitializeComponent();   
   }  
  
   [System.Web.Services.WebMethod]  
   [System.Web.Script.Services.ScriptMethod]  
   public  string MyMethod(string value)  
   {  
       return value;  
   }  
  
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru