Search code examples
asp.net-mvc-2master-pagesviewdata

Passing data from controller to master page - based on currently logged in user


Using MVC2

Have a master-page that needs to hide certain menus if currently logged in user does not have correct flags set.

Seems like a common problem. Found examples that require that all controllers inherit from a base controller (I have that) and where in constructor of the base controller, the passing of certain parameters to ViewData can occur. This is great and would be easy for me to do, but User.Identity and Request objects are NULL during the construction of base controller.

How do I get to User.Identity of the currently logged in user so that I can query database & modify the ViewData collection accordingly before Master Page view is rendered?

Thanks


Solution

  • You could use child actions along with the Html.Action and Html.RenderAction helpers. So you could have a controller action which returns a view model indicating the currently logged in user info:

    public MenuController: Controller
    {
        public ActionResult Index()
        {
            // populate a view model based on the currently logged in user
            // User.Identity.Name
            MenuViewModel model = ...
            return View(model);
        }
    }
    

    and have a corresponding strongly typed partial view which will render or not the menus. And finally inside the master page include the menus:

    <%= Html.Action("Index", "Menu") %>
    

    This way you could have a completely separate view model, repository and controller for the menu. You could still use constructor injection for this controller and everything stays strongly typed. Of course there will be a completely different view model for the main controller based on the current page. You don't need to have base controllers or some base view model that all your action should return.