2012-04-16 40 views
1

我创建了一个ApplicationController.cs,其他所有控制器都继承它。我试图用这个控制器从DB中捕获用户的全名,在layout.cshtml中设置为ViewBag &捕获。MVC3 - 从DB获取信息并填充到layout.cshtml

我还在Global.asax中创建了一个捕获用户登录的会话变量。我的问题是ApplicationController.cs中的Session变量为空。但是,会话变量已在所有子控制器中正确填充。这里是我的ApplicationController.cs代码:

public abstract class ApplicationController : Controller 
{ 
    private SkadPROEntities db = new SkadPROEntities(); 

    public SkadPROEntities SkadProDB 
    { 
     get { return db; }     
    } 


    public ApplicationController() 
    { 
     //string[] currentUserString = User.Identity.Name.Split('\\'); 
     //string myCurrentUser = currentUserString[1]; 
     //string myCurrentUser = Session["currentUser"].ToString(); 
     var empQuery = from employee in db.PRO_LSN_EMPLOYEE_OBJ 
         //where employee.LSN_Security_Nbr == Session["currentUser"].ToString() 
         where employee.LSN_Security_Nbr == "bhopkins" 
         select employee; 
     string firstName = ""; 
     foreach (var myEmployee in empQuery) 
     { 
      firstName = myEmployee.LSN_cf_First_Name; 
     } 
     ViewBag.FirstName = firstName; 
     ViewBag.EmpName = "Bill Test"; 
    } 
} 

为什么在ApplicationController.cs会话变量为空,但填充在所有的孩子控制器?

回答

1

您无法在构造函数中访问会话变量。大概你试图访问你的子构造函数中的会话变量,而不是它们的构造函数。

请参阅Session null in ASP.Net MVC Controller Constructors

+0

对于向布局页面注入数据信息,您有任何建议吗?我认为通过基本控制器会是最好的,但我需要访问会话变量。 – user1336495 2012-04-16 14:38:22

+0

@ user1336495我认为基础控制器是布局页面数据应该被提取的地方。您可以重写“OnActionExecuting”方法并在那里获取它。这就是说我不喜欢在布局中使用ViewBag。我会在布局中调用“@ Html.Action”,以便您可以单独获取数据。 – DMulligan 2012-04-16 14:49:08