There two ways you can pass parameters (or send request with parameters) to a WebMethod from Ajax in JavaScript.
1) Passing parameters through the Ajax URL (or query strings)
2) Passing parameters through XMLHttpRequest send() method
By the way, you can call a WebMethod with multiple parameters using jQuery. Check this example.
Create WebMethod with two arguments
So, lets create the methods (in C# and VB), which will accept an Ajax request with multiple parameters.
As I said, there are two ways a WebMethod can receive multiple parameters. Therefore, I’ll create two methods: one will calculate the percentage, the other will do a simple addition.
The Web Service (C#)
using System; using System.Web; using System.Web.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod()] public double percentage(double leftOperand, double rightOperand) { var perc = (leftOperand / rightOperand) * 100; return Math.Round(perc); } [WebMethod] public int calculate_sum() { int val1 = int.Parse(HttpContext.Current.Request.QueryString["l"]); int val2 = int.Parse(HttpContext.Current.Request.QueryString["r"]); return val1 + val2; } }
Imports System.Web Imports System.Web.Services <System.Web.Script.Services.ScriptService()> _ <WebService(Namespace:="http://tempuri.org/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class WebService Inherits System.Web.Services.WebService ' Calculate the percentage. <WebMethod()> _ Public Function percentage(ByVal leftOperand As Double, ByVal rightOperand As Double) As Double Dim perc = (leftOperand / rightOperand) * 100 Return Math.Round(perc) End Function ' Calculate the sum of two values. <WebMethod()> _ Public Function calculate_sum() As Integer Dim val1 As Integer = HttpContext.Current.Request.QueryString("l") Dim val2 As Integer = HttpContext.Current.Request.QueryString("r") Return val1 + val2 End Function End Class
I’ll add few HTML elements like textboxes to accept inputs and a button to call the script.
<body> <div> <input type="radio" id="sum" name="t1" checked /> <label for="sum">Calculate Sum</label> <input type="radio" id="percent" name="t1" /> <label for="percent">Calculate %</label> <p>Enter a number <input id="val1" /></p> <p>Enter a number <input id="val2" /></p> <p><input id="bt" type="button" value="Calculate" onclick="cal()"/></p> </div> <div id='t1'></div> </body>
The Script to call the Web Service Methods with Parameters
<script> let cal = () => { // get input values. let v1 = document.getElementById('val1').value; let v2 = document.getElementById('val2').value; const oXHR = new XMLHttpRequest(); oXHR.onreadystatechange = reportStatus; // 1st method (calculate the sum of two numbers) if (document.getElementById('sum').checked) { oXHR.open("POST", "WebService.asmx/calculate_sum?l=" + v1 + "&r=" + v2, true); oXHR.setRequestHeader("Content-Type", "application/json"); oXHR.send(); // send request. } // 2nd method (get the percentage) if (document.getElementById('percent').checked) { oXHR.open("POST", "WebService.asmx/percentage", true); var params = "{ 'leftOperand': '" + v1 + "', 'rightOperand': '" + v2 + "' }"; oXHR.setRequestHeader("Content-Type", "application/json"); oXHR.send(params); // send request with parameters. } function reportStatus() { let ele = document.getElementById('t1'); if (oXHR.readyState === XMLHttpRequest.DONE && oXHR.status === 200) { let val = JSON.parse(this.responseText); if (document.getElementById('percent').checked) { ele.innerHTML = 'the value is: ' + val.d + "%" ; } else ele.innerHTML = 'the value is: ' + val.d; } } } </script>
I have explained about XMLHttpRequest objects in detail here.
The 1st method is making a POST request with a URL with two arguments (or parameters). The method "calculate_sum()" gets the parameters (or the values) through the QueryString() method. See the Web methods again.
The 2nd method is also making a POST request. However, the URL has no parameters or query strings. The parameters are passed using the send() method.
oXHR.send(params);
Remember, XMLHttpRequest "send()" method accepts an optional parameter. You can pass multiple parameters to a web service using the method.
You can learn more about JavaScript Ajax POST and GET methods here.