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.
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e) { Session["UserName"] = "Administrator"; } [System.Web.Services.WebMethod] public static string GetSessionValue(string key) { return HttpContext.Current.Session[key].ToString(); }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Get Session value from JavaScript in ASP.NET using JQuery ajax</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <script type="text/javascript"> function GetLoginUser() { $.ajax({ type: "post", url: "Default.aspx/GetSessionValue", contentType: "application/json; charset=utf-8", dataType: "json", data: '{"key":"UserName"}', success: function (result) { OnSuccess(result.d); }, error: function (xhr, status, error) { OnFailure(error); } }); } function OnSuccess(userName) { document.getElementById("lbUserName").innerHTML = userName; } function OnFailure(error) { alert(error); } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="Show User Name" onclick="GetLoginUser()" /> <label id="lbUserName"> This is currently logged in user name</label> </div> </form> </body> </html>
Advertisement