Search This Blog

Wednesday 12 August 2015

Get session value in javascript or access session value in javascript asp.net or get session value in javascript asp.net

Step 1:- Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind=" Default.aspx.cs" Inherits="Demo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get Session Value in Javascript</title>
    <script type="text/javascript">
        function GetSessionValue() {

            //Make sure that you have defined the session variable

            var sessionValue = '<%=Session["Name"]%>';


            alert(sessionValue);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Get Session Value"/>
        </div>
    </form>
</body>
</html>

Step 2:- Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Attributes.Add("onclick""return GetSessionValue();");

            Session["Name"] = "Rajesh";
        }
    }
}

Example:



 

Note:-

Instead of using below line in code behind or .cs page.

Button1.Attributes.Add("onclick""return GetSessionValue();");

You can also use the below line in design page to bind the javascript function with button event.

<asp:Button ID="Button1" runat="server" Text="Get Session Value" OnClientClick="return GetSessionValue();"/>


No comments:

Post a Comment