简体   繁体   中英

Best way to handle multiple Models in one View

I'm a bit new to ASP.Net MVC, but am trying to understand when and how best to use ViewModels.

In many of my Views, the data required is only partially what resides in one Model. For that, I'm using AutoMapper to map the Model to the ViewModel and then passing the ViewModel to the View.

However, in other views, data from multiple Models are required.

The way I have been accomplishing this so far is like so:

public class GamesEditData
{
    public Game Game { get; set; }
    public ICollection<Genre> Genres { get; set; }
}

...where Game and Genre are Models. I feel like I'm doing something wrong here, though, since this is directly passing the Models themselves to the View. This is different than the other times where I am passing properties from a separate ViewModel, which makes me think I'm breaking some kind of pattern.

In short, what is the best way to populate the View with multiple Models using a ViewModel design pattern in ASP.Net MVC?

Yeah, that's exactly how I'd do it. It's simple and easy to extend later if you need to add more elements to the model or decorate the model with attributes.

Alternatively, you could use a Tuple , declaring your model type as:

@model Tuple<Game, ICollection<Genre>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM