问题
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:
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.
回答2:
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"]%>;
回答3:
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
来源:https://stackoverflow.com/questions/16031917/how-to-create-session-variable-and-retrieve-in-javascript-mvc3