Friday, 25 April 2014

Call ASP.NET WebService using JQuery and JavaScript

Description:

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 different type of examples to call webservice from JavaScript client side code in ASP.NET.

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

Summary:

Call WebService from JavaScript using ScriptManager without JQuery

   You can call WebService method from JavaScript using ScriptManager's ServiceReference. To use this you need to add ScriptManger tag in your page and include the ServiceReference. Here, I have written an example to get web server time via WebService method with ScriptManager's Ajax call in ASP.NET C#.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService method from JavaScript without JQuery</title>
    <script type="text/javascript">
        function CallWebService() {
            MorganWebApp.WebService1.GetServerTime(OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptmanager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService1.asmx" />
        </Services>
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show Server Time" onclick="CallWebService()" />
        <label id="currentDate">
            Current Date Time in Web Server from WebService method</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [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 WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}

Call WebService from JavaScript with Parameters using ScriptManager

Calling webservice method with multiple parameters from JavaScript is an another frequently required need . Here, I have written the example to pass two int type parameters to add value in WebService method without using JQuery.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService method from JavaScript without JQuery</title>
    <script type="text/javascript">
        function CallWebService() {
            var val1 = document.getElementById("val1").value;
            var val2 = document.getElementById("val2").value;
            MorganWebApp.WebService1.AddValues(val1,val2,OnSuccess, OnFailure);
        }
        function OnSuccess(result) {
            if (result) {
                document.getElementById("result").innerHTML = result;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptmanager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService1.asmx" />
        </Services>
    </asp:ScriptManager>
    <div>
    A:<input id="val1" type="text"/> B:<input id="val2" type="text"/>
        <input type="button" value="Add" onclick="CallWebService()" />
        <label id="result">
            Shows result calcuated from from WebService method</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [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 WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public int AddValues(int a,int b)
        {
            return a + b;
        }
    }
}

Call WebService method from JavaScript with multiple parameters



Call WebService from JavaScript using JQuery ajax in ASP.NET C#

   You can call webservice method from JavaScript client side using JQuery ajax method in C# ASP.NET.
Note: You need to add reference for JQuery script file to use JQuery ajax.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService from JavaScript using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function CallWebService() {
            $.ajax({
                type: "post",
                url: "WebService1.asmx/GetServerTime",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="CallWebService()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [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 WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}


Call WebService from JavaScript using JQuery ajax with Parameters

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

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService from JavaScript using JQuery ajax with Parameters</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function CallWebService() {
            var val1 = document.getElementById("val1").value;
            var val2 = document.getElementById("val2").value;
            $.ajax({
                type: "post",
                data:"{'a':'" + val1 + "','b':'" + val2 + "'}",
                url: "WebService1.asmx/AddValues",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(result) {
            if (result) {
                document.getElementById("result").innerHTML = result;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       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>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{

    [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 WebService1 : System.Web.Services.WebService
    {        
        [WebMethod]
        public int AddValues(int a,int b)
        {
            return a + b;
        }
    }
}

Related Articles:


Advertisements
Advertisements

No comments:

Post a Comment