How to call Asp.Net WebMethod using JavaScript Ajax

← PrevNext →

Using Ajax XMLHttpRequest object and POST method. Yes, you can easily call an Asp.Net WebMethod from JavaScript using Ajax and I’ll you how simple it is.

Follow these steps to create a web service using WebMethod in Asp.Net.

1) Create a new Asp.Net project and open it.

2) Right click the website in the Solution explorer and select Add New Item….

3) From the Templates list select Web Service and click the Add button.

You can choose your preferred language, C# or Visual Basic.

4) The default name of the web service will be WebService.asmx, which is loaded in Root directory of your project. It will also create a Class name WebService.cs (WebService.vb for Visual Basic) in App_Code folder.

Now, lets create our web service.

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 string greet()
    {
        string msg;
        String hour = DateTime.Now.ToString("HH");

        if (int.Parse(hour) < 12)
            msg = "Good Morning";
        else if (int.Parse(hour) >= 12 & int.Parse(hour) <= 17)
            msg = "Good Afternoon";
        else
            msg = "Good Evening";

        return "<b>" + msg + "</b>" + " friend, I am Arun Banik";
    }
}

It’s a simple WebMethod. Doesn’t take any parameter(s) or do any calculations. It simply receives a call from a JS code using Ajax and responds by returning a message (a string).

The Web Service (Vb)
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

    <WebMethod()> _
    Public Function greet() As String
        Dim msg As String

        If DateTime.Now.ToString("HH") < 12 Then
            msg = "Good Morning"
        ElseIf DateTime.Now.ToString("HH") >= 12 And DateTime.Now.ToString("HH") <= 17 Then
            msg = "Good Afternoon"
        Else
            msg = "Good Evening"
        End If

        Return msg & " friend, I am Arun Banik"
    End Function
End Class

JavaScript Ajax to Call the Web Method

<body>
    <p><input id="bt" type="button" value="Call Web Method" onclick="greetings()"/></p>
    <div id='t1'></div>
</body>

<script>
    let greetings = () => {
        const oXHR = new XMLHttpRequest();
        oXHR.onreadystatechange = reportStatus;

        oXHR.open("POST", "https://www.encodedna.com/c-sharp/WebService.asmx/greet", true);  
            // you can also provide the complete URL. Like, https://www.encodedna.com/c-sharp/WebService.asmx/greet 
        oXHR.setRequestHeader("Content-Type", "application/json");
        oXHR.send();        // Send the request.

        function reportStatus() {
            let ele = document.getElementById('t1');

            // Check if there is a response.
            if (oXHR.readyState === XMLHttpRequest.DONE && oXHR.status === 200) { 
                let val = JSON.parse(this.responseText);        // get the response, the value.
                ele.innerHTML = val.d;      // show it.
            }
        }
    }
</script>

If everything works correctly, the Ajax call will get a response (or receive a message) by greeting the user like good morning, evening etc. based on the time.

Well, you can greet your users using plain JavaScript. There’s no need to call a web service for that. This is just an example to show how to call a Web Method from JavaScript using Ajax.

In fact, you do more advanced operations using JavaScript Ajax and WebMethod. Like calling a WebMethod to extract data from an SQL Server table, run an algorithm at the server side, or do some calculations and return the result etc.

You can also pass single or multiple parameters to a WebMethod using JavaScript Ajax.

← PreviousNext →