How to create session variable and retrieve in JavaScript MVC3

流过昼夜 提交于 2019-12-25 03:39:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!