【问题标题】:Define session variable in c# get it from javascript在c#中定义会话变量从javascript获取它
【发布时间】:2015-12-15 21:07:38
【问题描述】:

我正在从后面的代码中保存表示会话变量中 URL 的字符串,如下所示:

        String mois = Request.QueryString["mois"].ToString();
        String m = mois;


        String moisnom = Request.QueryString["moisnom"].ToString();
        String annee = Request.QueryString["annee"].ToString();
        String dt = Request.QueryString["date"].ToString();
        String user = Request.QueryString["user"].ToString();
        String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
        Session["togo"] = where; 

然后我尝试在 JavaScript 中像这样:

    var togo = '<%=Session["togo"]%>';
    //  i also tried this var togo ='@Session["togo"]'; 
    var newPage = togo; // this should contain a string with the url to go to 

但是当我使用它时,它会将它用作字符串,这就是我的 URL 的样子:

http://localhost:50311/<%=Session["togo"]%>
 or
http://localhost:50311/@Session["togo"]

我还能如何访问会话变量或者我做错了什么?

 EDIT: 
like you suggested i already tried using the hidden field like this 

     yes  i tried that but then i had this problem here is the definition of the hidden field  

             <input type="hidden" value="aa" id="myHiddenVar" runat="server"/>

然后我尝试在点击时给它我需要的值

            String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
        myHiddenVar.Value= where; 

这就是我尝试从 js 文件中获取它的方式

       var togo = $('#myHiddenVar').val();
       var newPage = togo;

但它采用默认值表示“aa”,因为 value="aa" 我猜是因为脚本在分配变量之前执行,如何反转该顺序?

【问题讨论】:

  • 那个 javascript 在单独的 js 文件中吗? asp.net 特定语法 (&lt;% .. %&gt;) 在那里不起作用,仅在由 asp.net 引擎处理的文件(aspx、ascx、cshtml)中。
  • 是的,它在一个 js 文件中,你知道任何有关如何从 js 文件功能中获取会话变量的链接吗?
  • 如果它位于不同的 js 文件中而不是您无法访问它 即 scriplet 标签仅适用于 aspx 页面...
  • 只需从您的 aspx 页面中删除 value 参数...不要分配任何东西!从后面的代码中赋值...
  • 是的,现在它可以工作了!!只需编辑隐藏标签的 value 属性 Value="0 " 。即使您可以删除 value 属性

标签: javascript c# session


【解决方案1】:

会后["togo"] = where; 将此 Session["togo"] 保存在隐藏变量中

hiddenVariable=Session["togo"];

现在在 JS 中访问隐藏变量: 假设隐藏变量的 ID 是“hdnxyz”

var togo = $('#hdnxyz').val();

var newPage = togo;

【讨论】:

  • 是的,现在它可以工作了!!只需编辑隐藏标签的 value 属性 Value="0 " 。即使您可以删除 value 属性
  • 是的,它有效,但它采用默认分配的值而不是我想要的值
  • 不要给它分配默认值,好吗?
  • 好的,然后创建 JS 函数并在该函数内部执行访问隐藏变量的工作
【解决方案2】:

首先会话驻留在服务器上!!!!!!

如果它在不同的 js 文件中而不是您无法访问它 即 scriplet 标签仅适用于 aspx 页面...

所以没有办法在客户端访问会话变量..

而是将您的 sessio9n 值分配给隐藏变量,然后使用 javascript 访问它

【讨论】:

    【解决方案3】:

    asp:HiddenField 中写入 Session 元素,然后使用您的 js 代码从中读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多