Saturday, 3 May 2014

Call ASP.NET WebService using JQuery with Parameters


   The AJAX functionality of ASP.NET enables you to call ASP.NET Webservice's methods from JavaScript. This enhances the user experience for the Web application. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server. In this article, I am going to write and explain about how to Call WebService function with parameters from JavaScript using JQuery  in ASP.NET.

To enable WebService calls from script, an .asmx Web service class should qualified with the ScriptService ([System.Web.Script.Services.ScriptService]) attribute and individual methods or functions should be qualified with [WebMethod] attribute.
    public class WebService1 : System.Web.Services.WebService
        public string HelloWorld()
            return "Hello World";

Call WebService from JavaScript using JQuery ajax with Parameters:

    You can call webservice method or function from JavaScript in ASP.NET using JQuery ajax method with single or multiple parameters. Here, I have written JQuery ajax example to call Add function in webservice by passing two Int parameters.

<head id="Head1" runat="server">
    <title>Call WebService from JavaScript using JQuery ajax with Parameters</title>
    <script type="text/javascript"
    <script type="text/javascript">
        function CallWebService() {
            var val1 = document.getElementById("val1").value;
            var val2 = document.getElementById("val2").value;
                type: "post",
                data:"{'a':'" + val1 + "','b':'" + val2 + "'}",
                url: "WebService1.asmx/AddValues",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                error: function (xhr, status, error) {
        function OnSuccess(result) {
            if (result) {
                document.getElementById("result").innerHTML = result;
        function OnFailure(error) {
    <form id="form1" runat="server">
       A:<input id="val1" type="text"/> B:<input id="val2" type="text"/>
        <input type="button" value="Add" onclick="CallWebService()" />
        <label id="result">
            Shows the result calculated from WebService method</label>

namespace MorganWebApp

    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX,
    // uncomment the following line. 
    public class WebService1 : System.Web.Services.WebService
        public int AddValues(int a,int b)
            return a + b;
Output: Call WebService method from JavaScript with Parameters using JQuery

Call WebService from JavaScript with Parameters using JQuery

Related Articles:


No comments:

Post a Comment