WebMethod and ScriptMethod Attributes in .NET Webfroms

In Web forms, .Net applications to call the client side scripts like javascript and Jquery web calls are handled by using WebMethod and ScriptMethod Attributes. This method uses the shared function keyword from server-side pages. The function which mentioned with Shared keyword and WebMethod attribute exposed by WebService will send Post and get a request on that. For sharing json format data also same kind of web method will be used. The code example is given below.

Server End code

Public Class WebCall
    Inherits System.Web.UI.Page
    <WebMethod()>
    <ScriptMethod()>
    Public Shared Function GetServerTime() As String
        Return DateTime.Now.ToString()
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        ' No server-side logic needed for this example.
    End Sub
End Class

From the client end, an OnClick event will be sent a request for getting a server date & timely response. The client-side code example is below.


<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><main>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
        function callWebMethod() {
            alert("callweb");
            $.ajax({
                type: "POST",
                url: "WebCall.aspx/GetServerTime",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);
                    $("#lblTime").text(msg.d);
                },
                error: function (xhr, status, error) {
                    alert("Error: " + xhr.responseText);
                }
            });
        }
    </script>    
    <div>
      
  <button type="button" onclick="callWebMethod()">Get current server time</button><p id="btnGetTime"></p>
          <label id="lblTime" Text=""></label> 
    </div>
    </main>
</asp:Content>

Output

 Get current server time

Up Next
    Ebook Download
    View all
    Learn
    View all