John Livermore
John Livermore

Reputation: 31313

Pattern for passing common data to _layout.cshtml in MVC4.5

I am trying to come up with the best pattern for passing data to my _layout.cshtml page.

I am toying with creating a common base class from which all view specific models derive. This base class would be recognized by my _layout.cshtml and used to fill in details about the user and load proper images in the header, etc. For example, here is a snippet of it.

public abstract class ViewModelBase
{
    public string Username { get; set; }
    public string Version { get; set; }
}

At the top of my _layout.cshtml I have...

@model MyProject.Web.Controllers.ViewModelBase

I need a common area to hydrate the information required by the model, and am planning to use the following pattern...

  1. Each action method creates and hydrates a model derived from ViewModelBase.
  2. The action completes.
  3. I create a ActionFilterAttribute and override OnActionExecuted to cast the current Result to ViewModelBase.
  4. If the conversion is successful, then I populate the ViewModelBase details with the relevant data.

Here are my questions...

  1. Is the use of a ActionFilterAttribute (OnActionExecuted) a good pattern for what I am trying to do?
  2. I am not able to see how to get the Result created in the action from the HttpActionExecutedContext. How is this done?

Upvotes: 4

Views: 1870

Answers (1)

Andy T
Andy T

Reputation: 9881

I follow the same approach and use a base ViewModel class which all my other viewModels inherit from.

Then, I have a base controller that all controller inherit from. In there, I have one method that takes care of initializing the view model:

protected T CreateViewModel<T>() where T : ViewModel.BaseViewModel, new()
{
    var viewModelT = new T {
                        HeaderTitle = "Welcome to my domain",
                        VisitorUsername = this.VisitorUsername,
                        IsCurrentVisitorAuthenticated = this.IsCurrentVisitorAuthenticated,

                        //...
                    };

    return viewModelT;
}

Then on each controller, when I want to create the view model, I simply call the base controller's method:

var vm = base.CreateViewModel<MyPageCustomViewModel>();

Upvotes: 3

Related Questions