views:

36

answers:

1

I have an asp.net masterpage, and All my controllers inherit from a controller base. All my view models inherit from ViewBase. How can I have a base set of data in the master page that is populated from the base controller into the viewbase, then into the masterpage?

A: 

What I have done in the past is used ViewData to populate my master page.

Inside your master page you can put:

<% var baseModel = ViewData["baseModel"] as BaseViewModel; %>

then

baseModel.xx for whatever properties you need throughout your masterpage.

In my ControllerBase, I then override OnActionExecuting and popluate the viewData with an instance of my baseViewModel.

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        if (filterContext.Canceled || filterContext.Exception != null)
            return;

         var viewResult = filterContext.Result as ViewResult;
         var viewModel = new BaseViewModel();
         PopulateBaseViewModel(viewModel);
         viewResult.ViewData["baseModel"] = viewModel;            
    }
Climber104