How to call webservice method by asp.net ajax.


Its very easy to call webservice method from client side using asp.net ajax. Following steps are the minimal things needed to

call webservice method from asp.net page using asp.net ajax :

1. Create a asp.net website using Visual studio(Here I am using Visual studio 2010), Lets name it WSCallFeatureTest.

2. Now add a new webform lets name it CallWebservice.aspx.

3. Add a new webservice file(.asmx) name it WebService.asmx

4. Add a webservice method to the WebService.asmx file. Below is the sample method by which I will test.

The content of the webservice class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

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

}

5. Now its time to call the webservice method HelloWorld from the webform. To call the webservice method from the webform
have to add the ScriptManager to the page and have to add the webservice referrence to the page. The following content serve

this things.
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true”>
<Services>
<asp:ServiceReference Path=”~/WebService.asmx” />
</Services>
</asp:ScriptManager>

and a button will be added to the page this button will call the webservice method. The total content of the web form is

given below :

<%@ 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”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script type=”text/javascript” language=”javascript”>

function GetWSValue() {

WebService.HelloWorld(WsCompleted);

return false;
}

function WsCompleted(result) {

if (result != null) {
alert(result);
}
}

</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true”>
<Services>
<asp:ServiceReference Path=”~/WebService.asmx” />
</Services>
</asp:ScriptManager>
<table>
<tr>
<td>
&nbsp;
</td>
<td>
<asp:Button ID=”btnGetValue” runat=”server” Text=”GetWSValue” OnClientClick=”return GetWSValue();”  />
</td>
</tr>
</table>
</form>
</body>
</html>

6. Clicking on the button will call webservice method HelloWold and will show the result on the alert.

Advertisements