如何在c# asp.net mvc中从控制器获取会话变量值到ajax调用



我想从mvc控制器actionresult中获取会话变量值,它返回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#代码
[HttpPost]
public ActionResult accountLogin(){
Session[Keys.accountrole] = "value";
return View("_viewpage");
}

当前的实现是返回未定义的会话变量,或者它将显示@session关键字本身而不是其中的值。

只能在服务器端访问Session。所以你需要在动作中获取Session变量值并以json值返回

试试这个

[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};
}
ajax

success: function (data) {
var testUser = data.accountRole;
alert(testUser);

最新更新