Fri, 17 May 2024


How to call an ASP.NET web service from client script?

By: Peter, NetArt Media
Tue, 26 January 2021

A very simple web service to add 2 numbers:

<%@ WebService Language="C#" class=MyMath %>

using System;
using System.Web.Services;

public class MyMath
{

[WebMethod]
public int add(int a, int b)
{
return a + b;
}

[WebMethod]
public int subtract(int a, int b)
{
return a - b;
}

}

A simple test page:

<html>
<head>
<script language="JavaScript">
var iCallID;

function init()
{
service.useService("ws2.asmx?WSDL","math");
}

function onmyresult()
{
if((event.result.error)&&(iCallID==event.result.id))
{
var xfaultcode = event.result.errorDetail.code;
var xfaultstring = event.result.errorDetail.string;
var xfaultsoap = event.result.errorDetail.raw;

// Add code to output error information here
alert("Error ");
}
else
{
service.innerHTML= "The method returned the result : " + event.result.value;
}
}


function tst()
{
iCallID = service.math.callService("Add",ip1.value,ip2.value);
}

</script>
</head>
<body onload="init();">
<BR>
Enter first Value <input type='text' id='ip1'>
<BR>
Enter Second value <input type='text' id='ip2'>
<BR>
<button onclick=javascript:tst()>Call Add Web Method</button>
<div id="service" style="behavior:url(webservice.htc)" onresult="onmyresult();">
</div>

</body>
</html>


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox