简体   繁体   English

如何在javascript中创建会话并在控制器mvc中访问它

[英]how to create session in javascript and access it in controller mvc

I have an mvc project.我有一个 mvc 项目。 i want to create a session in javascript, and be able to access it in the controller of the page.我想在 javascript 中创建一个会话,并且能够在页面的控制器中访问它。 i've tried different options, but none worked for me... one of the things i tried was:我尝试了不同的选择,但没有一个对我有用......我尝试过的一件事是:

View:看法:

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

but the value didn't go through to the action in the controller - there the value was null.但该值没有通过控制器中的操作 - 那里的值为空。

Controller:控制器:

var a=Session["TestingSession"];

any ideas?有任何想法吗?

Javascript is server side you would have to pass the variable to the server via ajax. Javascript 是服务器端,您必须通过 ajax 将变量传递给服务器。

The easiest way (personal opinion) to conduct an ajax request is to use jQuery library.进行ajax请求的最简单方法(个人意见)是使用jQuery库。

This is how to do an ajax request in 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");
        }
  });
})

for more info n jQuery ajax follow this link > http://api.jquery.com/jquery.ajax/有关 jQuery ajax 的更多信息,请点击此链接 > http://api.jquery.com/jquery.ajax/

$(function(){ 
  $.ajax({
    url     :'ajax page url',
    method  :'get/post',
    data     : variable containing data,
    success:function(html)
     {
       alert('success');
     }
  })
});

and than add values in session on the ajax page然后在 ajax 页面上的会话中添加值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM