Steps
- Go to New Project
- Select Language Visual C#
- Select Web
- Select ASP .NET Empty Web Application
- Give a proper Name to your Web App like WSFromHTMLusingJS
Now Add a HTML File to the Project.
For this, Right-click on the Project, choose Add a New Item, and choose the HTML template.
Name this like AddNumbersForm.html
This is a simple HTML Form taking three Numbers as input parameters
<!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>
<title>Add Three Nos</title>
<script type="text/javascript">
function Init() {
service.useService("WebService1.asmx?wsdl", "MyMath");
}
var num1, num2, num3;
function AddNos() {
num1 = document.additionForm.num1.value;
num2 = document.additionForm.num2.value;
num3 = document.additionForm.num3.value;
iCallID = service.MyMath.callService("AddThreeNos", num1, num2, num3);
}
function ShowResult() {
alert(event.result.value);
}
</script>
</head>
<body onload="Init()" id="service" style="behavior:url(webservice.htc)" onresult="ShowResult()">
<form name='additionForm'>
<table cellpadding='10' align='center'>
<tr>
<td colspan="2" align="center">Add Three Numbers</td>
</tr>
<tr>
<td>Number 1: </td>
<td><input type="text" name ="num1" size="10" maxlength ="5" /> </td>
</tr>
<tr>
<td>Number 2: </td>
<td><input type="text" name ="num2" size="10" maxlength ="5" /></td>
</tr>
<tr>
<td>Number 3: </td>
<td><input type="text" name ="num3" size="10" maxlength ="5" /></td>
</tr>
<tr> <td colspan="2" align="center"><br/><br/>
<button onclick="AddNos()">Add</button>
<input type="reset" value ="Reset" />
</td></tr>
</table><br/><br/>
</form>
</body>
</html>
Now Add a Web Service to the Project
For this, Right-click on the Project, choose Add a New Item, and choose the Web Service template.
Name this WebServiceTest.asmx
When you create the web service by default you get a web method called Hello World.
Put this code below that and run your web service
[WebMethod]
public int AddThreeNos(int num1, int num2, int num3)
{
return num1 + num2 + num3;
}
Here to keep things simple we have created a very simple Web Service that returns the sum of three integer variables.
For calling webservices in HTML using JavaScript you need another file called webservice.htc
You can download this file from here.
Web Service Behavior can be used to call remote methods from Web Services. The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.
Download this file and put it in your Project Directory.
Run the project. You are done now. Congrats for Calling a WebService from an HTML Page using JavaScript.
Snapshot of the o/p

Addition No Form

Result from WebService
P.S-Try this only in Internet Explorer. You may not get the desired results in other browsers.




