Hello all,
To call a web service from JavaScript using ASP.NET AJAX, there are certain steps that you have to follow which are listed bellow :
Decorate web service class with
[System.Web.Script.Services.ScriptService]
Include ScriptManager control on the WebForm from which you want to call your web service and specify the path of the web service
<asp:ScriptManager runat="server">
<Services>
<asp:ServiceReference Path="~/GetData.asmx" />
</Services>
</asp:ScriptManager>
Now within the JavaScript, you can give fully qualified name of the Web Method that you want to invoke of Web Service.
WebServiceApp.GetDataService.Add(fisrtNumber, secondNumber, onSuccess, onError);
To understand this example we have following code packet :
In APSX page, we have
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebServiceApp.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javescript">
function getServiceData() {
var fisrtNumber = document.getElementById("txtfirstNumber").value;
var secondNumber = document.getElementById("txtSecondNumber").value;
WebServiceApp.GetDataService.Add(fisrtNumber, secondNumber, onSuccess, onError);
}
function onSuccess(callBackResult) {
alert(callBackResult);
}
function onError(errors) {
alert(errors.get_message());
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server">
<Services>
<asp:ServiceReference Path="~/GetDataService.asmx" />
</Services>
</asp:ScriptManager>
<table>
<tr>
<td>Firts Number</td>
<td>
<asp:TextBox ID="txtfirstNumber" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Firts Number</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="button" value="Get Sum" onclick="getServiceData()" /></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<asp:Label ID="lblOutput" runat="server"></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
In C# we have, Code for the Web Service :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebServiceApp
{
/// <summary>
/// Summary description for GetDataService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.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 GetDataService : System.Web.Services.WebService
{
[WebMethod]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
}
}
0 Comment(s)