2014-10-22 50 views
1

我哈瓦2个控制器:ControllerA和ControllerB,以及在controllerA会议设定值,但在ControllerB不能获得价值,这样的代码:C#MVC会话是空

public class ControllerA : Controller 
{ 
    public ActionResult Index() 
    { 
     Session["a"] = "test"; 
    } 
} 

public class ControllerB : Controller 
{ 
    public ActionResult Index() 
    { 
     ViewBag.Test = Session["a"].ToString(); 
    } 
} 

我试图使用cookie来代替的会话,但有同样的问题。 我不知道我是否应该在C#MVC中使用会话,请让我知道是否有更好的会话。谢谢。

+0

http://stackoverflow.com/questions/560084/session-variables-in-asp-net-mvc – Simon 2014-10-22 11:09:16

+0

可以显示真实的代码,而不是样品 – 2014-10-22 11:10:04

+1

已经在这里回答了多个建议的解决方案: http://stackoverflow.com/questions/10629882/asp-net-mvc-session-is-null – Rimmon 2014-10-22 11:13:22

回答

0

首先创建SessionController.cs

public class SessionController 
{ 

    const string sessionname = "UserContext"; 
    public static SessionDetail UserContext 
    { 
     get 
     { 
      return System.Web.HttpContext.Current.Session[sessionname] as SessionDetail; 
     } 
     set 
     { 
      HttpContext.Current.Session[sessionname] = value; 
     } 
    } 

} 
public class SessionDetail 
{ 
     public string Employee_ID { get; set; } 
} 

继承该控制器的任何其他控制器,其中会话是使用

例如:

public class DashboardController : SessionController 
{ 
    SessionController.UserContext.Employee_ID = "1";//Assign Value 
    var empId = SessionController.UserContext.Employee_ID; //Use Value 
    .... 
} 

然后添加该代码到Global.asax

protected void Session_Start() 
{ 
    SessionDetail sdetail = new SessionDetail(); 
    SessionController.UserContext = sdetail; 
} 
+0

你可以添加更多的变量到SessionDetail类并使用它。 – ujval 2016-05-19 09:09:09