When view requires data from more than one model class, the most common and recommended approach is to create a view model. A view model is a custom class that encapsulates all the data necessary for a specific view, aggregating properties from multiple models or providing additional properties tailored for the view’s presentation needs.
Why Use View Models? Encapsulation: Keeps your view logic organized and prevents your views from becoming tightly coupled to your underlying business models. Flexibility: Allows you to combine data from different sources (multiple models, configuration settings, etc.) into a single object for the view. Type Safety: Strongly typed views with view models offer compile-time type checking and IntelliSense, improving development efficiency. Data Shaping: You can create properties in the view model specifically designed for how you want to display data in the view, such as formatted strings or calculated values.
Creating and Using View Models Define the View Model: Create a new class in your Models folder to represent the view model. This class will have properties to hold the data from the various models your view needs. Populate in the Controller: In your controller action, retrieve the data from your different models and use them to create an instance of your view model. Pass to the View: Pass the populated view model object to the view using the View method. Access in the View: In your view, use the @model directive at the top to specify the type of your view model. You can then access the view model’s properties using Model.<PropertyName>.
Code Example: PersonAndProductWrapperModel // PersonAndProductWrapperModel.cs (View Model) public class PersonAndProductWrapperModel { public Person PersonData { get; set; } public Product ProductData { get; set; } }
// HomeController.cs (Controller) public IActionResult SomeAction() { Person person = GetPersonData(); // Fetch person data Product product = GetProductData(); // Fetch product data
var viewModel = new PersonAndProductWrapperModel { PersonData = person, ProductData = product };