从模型访问BaseController属性

时间:2016-08-05 10:15:23

标签: asp.net-mvc asp.net-mvc-5

我在BaseModel中有一个属性来跟踪当前用户,如下所示:

    public class BaseController : Controller
    {
        public UserModel currentUser;

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            UserRepository userRep = new UserRepository();
            currentUser = userRep.getCurrentUser();
        }
    }

如何在我的模型中访问该变量,或者是否有办法在BaseModel中创建类似的内容?

1 个答案:

答案 0 :(得分:1)

您可以在视图中提供名称空间,如下所示:

@using TestMVCApp.Controllers
@{
     var currentUser = BaseController.currentUser;
}

<强> BaseController

public class BaseController : Controller
{
    public static UserModel currentUser;

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        currentUser.id = 5;
    }

}