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

久未见 提交于 2019-12-21 20:53:22

问题


I am using MVC3 with Razor View engine,

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.

how to achieve this..


回答1:


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.

Sample

jQuery

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

Mvc Controller

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

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

More Information

  • Save and retrieve Session data via Ajax using JQuery in an MVC 3 application


来源:https://stackoverflow.com/questions/16037538/how-to-create-session-variable-in-javascript-mvc3-razor-view-engine-cshtml

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