Skip to content Skip to sidebar Skip to footer

How To Pass Session Value From Code Behind To Javascript

i have made a session variable Session['Background1'] = value; in one of my code behind function i want to retrieve this value in my javascript function.

Solution 1:

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);

Solution 2:

Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:

var background1 = null; // TODO: Add value from session.

To add the value from session, all you need to do is this:

var background1 = '<%= Session["Background1"] %>';

When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.

I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.

Post a Comment for "How To Pass Session Value From Code Behind To Javascript"