In this article I will explain with an example, how to call server side methods using JavaScript and jQuery in ASP.Net using C# and VB.Net.
 
 
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing Name.
Button – For showing captured Name and current server time.
The Button has been assigned with a JavaScript onclick event handler.
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
 
 
Client Side Script
Inside the HTML, the following jQuery script file is inherited.
1.jquery.min.js
 
When the Button is clicked the ShowCurrentTime JavaScript function is executed which makes an AJAX call to the GetCurrentTime WebMethod.
The value of the TextBox is passed as parameter to the WebMethod.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script>
 
 
Namespaces
You will need to import following namespaces.
C#
using System.Web.Services;
 
VB.Net
Imports System.Web.Services
 
 
WebMethod (PageMethod)
The WebMethod accepts Name as parameter captured from the TextBox and returns a message to the user along with the current server time.
Note: The following WebMethod is declared as static (C#) and Shared (VB.Net), it is decorated with WebMethod attribute, this is necessary otherwise the method will not be called from client side jQuery AJAX call.
 
C#
[WebMethod]
public static string GetCurrentTime(string name)
{
    return"Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
 
VB.Net
<WebMethod>
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " &
        DateTime.Now.ToString()
End Function
 
 
Screenshot
Calling server side methods using JavaScript and JQuery in ASP.Net
 
 
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 
Demo
 
 
Downloads