【问题标题】:how to create session in javascript and access it in controller mvc如何在 javascript 中创建会话并在控制器 mvc 中访问它
【发布时间】:2017-03-07 10:46:44
【问题描述】:

我有一个 mvc 项目。我想在 javascript 中创建一个会话,并能够在页面的控制器中访问它。 我尝试了不同的选择,但没有一个对我有用...... 我尝试过的其中一件事是:

查看:

<script>
   @Session["TestingSession"]="Hello...";
</script>

但该值没有通过控制器中的操作 - 那里的值为 null。

控制器:

var a=Session["TestingSession"];

有什么想法吗?

【问题讨论】:

  • Session 是服务器端。 Javascript是客户端。您需要将值传递给服务器(例如使用 ajax)并将其设置在控制器中
  • 好的。我真的不知道如何使用ajax。你能给我更具体的指示吗?谢谢
  • 那么是时候做一些研究了:)

标签: javascript asp.net-mvc session controller


【解决方案1】:

Javascript 是服务器端,您必须通过 ajax 将变量传递给服务器。

进行ajax请求最简单的方式(个人意见)是使用jQuery库。

这是在 jQuery 中执行 ajax 请求的方法:

$(function () {

      $.ajax({
        method: "POST"
        ,data: {
            sessionVariable: variable
        }
        ,url: //enter the url of your controller/action which the session variable is being sent to, and handled by the server.
        ,success: function(returnedData){
            alert("Session successfully sent to the server");
            // you could return something from the controller with more info and display this using the returnedData object.
        }
        ,error: function(){
           alert("something went wrong");
        }
  });
})

更多信息 n jQuery ajax 请点击此链接 > http://api.jquery.com/jquery.ajax/

【讨论】:

    【解决方案2】:
    $(function(){ 
      $.ajax({
        url     :'ajax page url',
        method  :'get/post',
        data     : variable containing data,
        success:function(html)
         {
           alert('success');
         }
      })
    });
    

    然后在 ajax 页面上的会话中添加值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多