MVC3 - 从DB&获取信息填充layout.cshtml

时间:2012-04-16 14:20:03

标签: asp.net-mvc-3 razor

我创建了一个所有其他控制器都继承的ApplicationController.cs。我正在尝试使用此Controller从数据库中捕获用户的全名,设置为ViewBag&在layout.cshtml中捕获。

我在Global.asax中创建了一个会话变量来捕获用户的登录信息。我的问题是ApplicationController.cs中的Session变量为null。但是,会话变量在所有子控制器中正确填充。这是我的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中为null,但在所有子控制器中填充?

1 个答案:

答案 0 :(得分:1)

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

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