Now I will explain how to access or get session variable value in JavaScript or jQuery with example.
By using Session property we can easily access session values in JavaScript or jQuery based on our requirements. Following is the simple code snippet to get session values in values in JavaScript or jQuery.
JavaScript or jQuery Code
<script type="text/javascript">
$(function() {
var name = 'Welcome '+' <%=Session["UserName"] %>'
$('#lbltxt').text(name)
});
</script>
|
If you want complete example to access session values in JavaScript or jQuery open your aspx page and write the code like as shown following.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Asp.Net Access Session Variable Value in JavaScript or jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
var name = 'Welcome '+' <%= Session["UserName"] %>'
$('#lbltxt').text(name)
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label id="lbltxt" />
</div>
</form>
</body>
</html>
|
If you observe above code we are trying to get “UserName” session value in our client side using Session property.
Now open code behind file and write the code like as shown following
C# Code
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["UserName"] = "Guest";
}
}
|
VB.NET Code
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Session("UserName") = "Guest"
End Sub
End Class
|
Demo
When we run above code we will get result like as shown below
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.