0

I want to create a variable Session in JavaScript and Retrieve it in same JavaScript

My Code

  '<%Session["Test"] = "Welcome DS";%>';
        var session_value = '<%=Session["Test"]%>';
        alert(session_value);

its giving "<%=Session["Test"]%>" alert result, Its not giving Session values

1
  • I added the razor tag to your question, since the current question suggests that you are using a different view engine. Commented Apr 16, 2013 at 10:42

3 Answers 3

0

You are using a wrong syntax that is for another version of razor. You can change it to:

alert('@Session["Test"]');

Notice the use of the @ sign. You can refer to this page for the proper syntax.

Sign up to request clarification or add additional context in comments.

13 Comments

You don't have to use the razor engine. You can still use the traditional asp.net syntax.
If I can try it now, I will. The OP tagged his question as MVC 3 so I assume the project is in MVC 3 and that syntax won't work. The <%= =%> will no longer work.
again.. you don't have to use the Razor engine. On project creation you have the option to use the old view engine (default options are 'Razor' or 'ASPX'), in which case this will work perfectly. (This is still the case in MVC4)
We could have both asked the OP first then what engine he uses. I think I did mention that he is probably using a wrong razor engine.
@Yoeri, yes thank you, the same reason I did not downvote yours because I know that's valid too. Also, downvoting for me, is only for misleading or incorrect information that will never EVER work.
|
0

ASP.NET thinks what you write is a plain string. Removing the quotation marks should do the trick if we're talking about an .aspx file.

<%Session["Test"] = "Welcome DS";%>

var session_value = <%=Session["Test"]%>;

5 Comments

Without quotation marks its not working, its showing, warning near <%
could you verify that you are using the correct view engine? What is the extension of the file you are writing in?
The extension of file is .cshtml
Then you have, indeed, been writing the wrong syntax from the start.
either way you choose to change your project to the ASPX view engine, or you start reading this: haacked.com/archive/2011/01/06/…
0

If you really need your session variable only in Javascript why donøt you use a client side Session variable?

for example the html5 sessionStorage

You can set it like this:

sessionStorage.myVariable = "myvalue";

and read it like this:

var x = sessionStorage.myVariable

Comments

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.