如何在 JavaScript MVC3 Razor View engine .cshtml 中创建会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16037538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:00:30  来源:igfitidea点击:

How to Create Session Variable in JavaScript MVC3 Razor View engine .cshtml

javascriptasp.net-mvc-3razor

提问by Avinash Singh

I am using MVC3 with Razor View engine,

我正在使用带有 Razor View 引擎的 MVC3,

i have .cshtml page in that i have a JavaScript function, inside that JavaScript function, i want to create Session variable and retrieve that session in same JavaScript function.

我有 .cshtml 页面,因为我有一个 JavaScript 函数,在该 JavaScript 函数中,我想创建 Session 变量并在同一个 JavaScript 函数中检索该会话。

how to achieve this..

如何实现这一点..

回答by dknaack

Description

描述

The Session is on the server side so you need to call the server in order to set or retrieve session variables.

会话位于服务器端,因此您需要调用服务器以设置或检索会话变量。

Just post to a controller and set the Session variable there.

只需发布到控制器并在那里设置 Session 变量。

Sample

样本

jQuery

jQuery

$(function () {
    $.post('/SetSession/SetVariable', 
           { key : "TestKey", value : 'Test' }, function (data) 
    {
        alert("Success " + data.success);
    });
});

Mvc Controller

MVC控制器

public class SetSessionController : Controller
{
    public ActionResult SetVariable(string key, string value)
    {
        Session[key] = value;

        return this.Json(new { success = true });
    }
}

More Information

更多信息