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 using pure JavaScript and Ajax and I'll show you how simple it is to implement.

➡️ Web Service in Asp.Net

Follow these steps to create a web service 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);  
        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 good morning, evening etc. based on the time.

By the way, you can greet your users using plain JavaScript. There’s no need to call a web service for that.

In fact, you can do some 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. See this example.

← PreviousNext →