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.
2 Answers
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
2 Comments
Mishigen
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
David Hedlund
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.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
Mishigen
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
Paul Turner
That suggests that Code Blocks are not being evaluated in your page, which is another problem of itself.