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 orjQuery.
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 usingSession 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";
}
}
|


0 comments:
Post a Comment
Note: only a member of this blog may post a comment.