Skip to main content

Multiple Models in one View – ViewModels in ASP.NET MVC

Following on from my previous post on using ViewBag and TempData, this post will show you how to use ViewModels so that you can interact with multiple Models in one object and pass its properties to a View.

ViewModels are strongly typed, so they give you the following advantages over ViewBag:

  • Compile-time checking (ViewBag is dyanamically typed, so you’ll only see any issues at run time).
  • Intellisense (it’s worth using ViewModels for this functionality alone!)
  • Your Data Annotations in the ViewModel won’t be removed, like they are with Database Models when you add to/refresh the Entity diagram.

ViewModel Diagram

When we create a ViewModel, all we’re really doing is combining two Models from our database, into one ViewModel which will exist as a Class.

 

Creating a ViewModel

In Visual Studio I tend to keep my ViewModels in a ViewModels folder. But they can also be referenced from an imported DLL if required.

Continuing with the Car theme, here’s the ViewModel that we’d create:

 

Getting the data to the View, via the Controller

You create an instance of your ViewModel the same way you would create an instance of any other Model.

So we find the Car for the ID that’s been supplied. We then pass this car to another method CarToTuningCar which will convert the Car object into a TuningCarViewModel.

If you don’t have many properties to map, you can do it manually as shown below. But this can become time-consuming if you have lots of properties. In this case, you might want to try out AutoMapper.

We use the methods below to get the actual values from the Tuning table:

 

Rendering in the View

We need to ensure that the View uses our new ViewModel, so update it accordingly:

You can then access the properties of the ViewModel as usual:

 

Conclusion

ViewModels in ASP.NET allow us to work  with multiple Models and present their data in one View. Once you’ve got past the initial trickyness, you’ll find they over you advantages over using ViewBag and TempData.

Leave a Reply

Your email address will not be published. Required fields are marked *