[英]How to fetch Session variable value from a controller to ajax call in c# asp.net mvc
I want to fetch Session variable value from an mvc controller actionresult which returns a cshtml view.我想从返回 cshtml 视图的 mvc 控制器 actionresult 中获取 Session 变量值。 This ajax call is connected in a button click and is calling from a different cshtml.此 ajax 调用通过按钮单击连接,并从不同的 cshtml 调用。
function accountLogin() {
$.ajax({
url: accountLogin,
async: true,
type: 'POST',
cache: false,
success: function (data) {
var testUser = @Session[Keys.accountrole];
alert(testUser);
$("#navigationbar").empty();
$("#navigationbar").html(data);}
C# Code C# 代码
[HttpPost]
public ActionResult accountLogin(){
Session[Keys.accountrole] = "value";
return View("_viewpage");
}
The curent implementation is reaturning either undefined session variable or it will display the @session keyword itself not the value in it.当前的实现正在重新返回未定义的会话变量,或者它将显示 @session 关键字本身而不是其中的值。
You can only access Session on the server side.您只能在服务器端访问 Session。 So you have to get a Session variable value inside of the action and retun it back as a json value因此,您必须在操作中获取 Session 变量值并将其作为 json 值重新调回
Try this尝试这个
[HttpPost]
public IActionResult accountLogin(){
//I don't understand why you need it
Session[Keys.accountrole] = "value";
var sessionAccountRole=Session[Keys.accountrole];
return OK( {accountRole=sessionAccountRole} );
// or if you use an ancient net
return Json ( new {accountRole=sessionAccountRole} );
// or maybe
return new JsonResult {accountRole=sessionAccountRole};
}
and ajax和阿贾克斯
success: function (data) {
var testUser = data.accountRole;
alert(testUser);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.