Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle multiple Models in one View

Tags:

c#

asp.net-mvc

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?

like image 814
Dan Teesdale Avatar asked Dec 09 '25 23:12

Dan Teesdale


1 Answers

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>>
like image 159
p.s.w.g Avatar answered Dec 12 '25 13:12

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!