How to access WebMethod Session value in another page using jQuery Ajax in ASP.Net

Last Reply 2 months ago By AnandM

Posted 2 months ago

 default1.aspx page-

[WebMethod(EnableSession=true)]
public static void createdb(string dbname)
{

 HttpContext.Current.Session["database"] = dbname;

}

and i want to access and use session value to another page for instance default2.aspx

here is my code for retrieving session value

string sess_val = HttpContext.Current.Session["database"].ToString();

but  session is null

plz help me out

Posted 2 months ago

Hi mohdImran,

I have a created a sample which full fill your requirement.

You need to modify according to your requirement.

Default.aspx

<div id="dialog" style="background-color: aliceblue;">
    <input id="txt_db_name" type="text" runat="server" />
    <label id="lbl_db" runat="server">
    </label>
</div>
<div>
    <style>
        .ui-dialog-titlebar-close
        {
            visibility: hidden;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(document).ready(function () {
            var dialogDiv = $('#dialog');
            dialogDiv.dialog({
                title: 'Please Enter Database Name',
                draggable: false,
                resizable: false,
                closeOnEscape: false,
                model: true,
                autoOpen: true,
                buttons:
        {
            'Submit': createdb
        }
            });
        });

        function createdb() {
            var dbname = $('#txt_db_name').val();
            $.ajax({
                url: 'Default.aspx/createdb',
                type: 'POST',
                data: "{dbname: '" + dbname + "'}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function () {
                    window.location.href = 'Default2.aspx';
                }
            });
        }      
    </script>
</div>

Default.aspx.cs

[WebMethod(EnableSession = true)]
public static void createdb(string dbname)
{
    HttpContext.Current.Session["database"] = dbname;
}

Default2.aspx

<div>
    <asp:Label ID="lblSessionData" runat="server" />
</div>

Default2.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Session["database"].ToString()))
    {
        lblSessionData.Text = Session["database"].ToString();
    }
    else
    {
        lblSessionData.Text = "Empty Session Data.";
    }
}

ScreenShot

I agree, here is the link: http://e-iceblue.com/free-api