Thursday, 26 February 2015

Get Session value in JavaScript using JQuery ajax

In this article, I am going write C# and JavaScript code sample to access or check session value in JavaScript in ASP.NET using JQuery Ajax call.

Check Session value in JavaScript using JQuery ajax call:

You can access or get session variable value from JavaScript client side in ASP.NET using using JQuery ajax method. Check the below example to get session variable value in JavaScript using JQuery ajax call.

Note: You need to add reference for JQuery script file to use JQuery ajax method.

  protected void Page_Load(object sender, EventArgs e)
        Session["UserName"] = "Administrator";

    public static string GetSessionValue(string key)
        return HttpContext.Current.Session[key].ToString();
<html xmlns="">
<head id="Head1" runat="server">
    <title>Get Session value from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
    <script type="text/javascript">
        function GetLoginUser() {
                type: "post",
                url: "Default.aspx/GetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName"}',
                success: function (result) {
                error: function (xhr, status, error) {
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        function OnFailure(error) {
    <form id="form1" runat="server">
        <input type="button" value="Show User Name" onclick="GetLoginUser()" />
        <label id="lbUserName">
            This is currently logged in user name</label>


No comments:

Post a Comment