0

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.

1
  • Is there any specific point where you need the value? Like a click of a button or something! Commented Nov 29, 2009 at 23:02

2 Answers 2

3
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Sign up to request clarification or add additional context in comments.

2 Comments

i have added this code in codebehind function,when i retrieve it in javascript it says sessionValue is undefined,,i guess this statement defines a global variable sessionValue in javascript. in that case we need not have to define this variable explicitly
What the code snippet does is to generate the following piece of code (supposing Session["Background1"] returns red): <script type="text/javascript">var sessionValue = 'red';</script>. If you get an undefined-error, it's probably because your javascript that reads the value, is being executed before the rendered script. look at the rendered HTML to determine this. one solution might be to move the code that reads this value to a DOMReady or page load event listener.
1

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.

2 Comments

when i use alert(background) in my javascript function i get <%= Session["Background1"] %> as the alert message..i guess it is not at all evaluating any value and just showing the string used within the codes
That suggests that Code Blocks are not being evaluated in your page, which is another problem of itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.