Template for transferring shared data to _layout.cshtml in MVC4.5

I am trying to find the best template for transferring data to my _layout.cshtml page.

I play with creating a common base class from which all kinds of specific models are derived. This base class will be recognized by my _layout.cshtml and will be used to fill out details about the user and load the correct images in the header, etc. For example, here is a snippet.

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 I plan on using the following template ...

  • Each action method creates and moisturizes a model derived from ViewModelBase.
  • Action completed.
  • I create an ActionFilterAttribute and override OnActionExecuted to get the current result for ViewModelBase.
  • If the conversion is successful, I populate the ViewModelBase data with the appropriate data.

Here are my questions ...

  • Is using ActionFilterAttribute (OnActionExecuted) a good template for what I'm trying to do?
  • I cannot see how to get the result created in the action from the HttpActionExecutedContext. How it's done?
+4
source share
1 answer

I take the same approach and use the base ViewModel class, which inherits all my other view models.

Then I have a base controller that everything inherits from the controller. There is 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 a view model, I simply call the base controller method:

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

Source: https://habr.com/ru/post/1494106/


All Articles