Static WebMethod in Code Behind WebForm

Why the WebMethod is static in code behind WebForm

This question occured to me a few days ago after many days of working with AJAX technology. I am calling code behind PageMethod, WebServices, WCF and Web API services to consume data using the ajax() function. When there is a necessity to consume data from code behind of the .aspx page we declare some static function and then we consume this function using the ajax() function.

The point to be noted when we declare a function in code behind, we declare it as static (otherwise it will not work). Here is a small example for a better understanding.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

using Newtonsoft.Json;

 

namespace clientProject

{

    public class person

    {

        public string name { get; set; }

    }

    public partial class callAJAX : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        { 

        }

       

//static WebMethod to serve ajax() call

        [WebMethod()]

        public static person GetData(string name)

        {

            person p= new person();

            p.name = name;

            return p;

        }

    }

}

Here is code to consume this GetData() function.
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <script src="JQuery.js" type="text/javascript"></script>

    <script>

            $(document).ready(function () {

    $('#btn').click(function () {

        var name = $('#name').val();

        jQuery.ajax({

            url: 'callAJAX.aspx/GetData',

            type: "POST",

            dataType: "json",

            data: "{'name': '" + name + "'}",

            contentType: "application/json; charset=utf-8",

            success: function (data) {

                alert(JSON.stringify(data));

            }

        });

    });

});

    </script>

</head>

<body>

    Name:-<input type="text" name="name" id ="name" />

    <input type="button" name="btn1" id="btn" value="ClickMe" />

</body>

</html>
 
We are getting the following output, that’s fine. Now return to our explanation. Why are we declaring the function as a static function?

static function

To understand this, let’s analyze the ”url” property of the client application. In this URL property we are specifying the "<file name>/<function name>". Please note that we did not create an object of the page class to call this function. As we know, the property of a static method “We can invoke a static method using it’s class name without creating an object of this specific class”.

This is the reason it’s necessary to declare WebMethod  as a static method. In the following we are seeing the “url” property of the ajax() method.

WebMethod as  static method

Ok, fine; so one obvious question occurs in this scenario. If the method is static then how to maintain the session within WebMethod? The Microsoft guys are very clever and they have given a smooth option to maintain the session in the WebMethod, just set the property of  the WebMethod  attribute of the static function as in the following.
 

[WebMethod(EnableSession= true)]

public static string GetData(string name)

{

   return HttpContext.Current.Session.SessionID;

} 

Now this WebMethod is ready to maintain session data. In the following example we will try to get the session ID by calling this method.

This small code is prepared to call this WebMethod:
 

$('#session').click(function () {

        jQuery.ajax({

            url: 'callAJAX.aspx/GetData,

            type: "POST",

            dataType: "json",

            contentType: "application/json; charset=utf-8",

            success: function (data) {

                alert(JSON.stringify(data));

            }

        });

  });
 
When I am browsing this code using one of my browsers I am getting this session ID.

Session ID

At the same time I am browsing this same URL in various browsers and the session ID is different.

different browser session ID

So, WebMethod is maintaining the session, great and cool.

Conclusion

In this article we have learned two important concepts, one is why WebMethd is static and the other is how to maintain the session in WebMethod. I hope you like this small  but informative article.

Up Next
    Ebook Download
    View all
    Learn
    View all