3
votes

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?

1
You can also create ViewModels for Game and Genre, then populate and use them in your GamesEditData ViewModel. - Henk Mollema
@HenkMollema Thanks. That might be what I end up doing to keep everything consistent and abstracted away from using the Models themselves. - Dan Teesdale

1 Answers

6
votes

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>>