Skip to main content

Multiple Models in one View – ASP.NET MVC ViewBag and TempData

If you’re new to web development in ASP.NET or perhaps you’re moving over from Web Forms, one aspect of MVC that can be tricky to get your head around is how to combine multiple Models in one View.

By default, Visual Studio will scaffold your Views so that they can only interact with one Model.

But what if you need your Controller Action to interact with more than one Model at a time?

Probably the “easiest” method and the one that you’ll see in most of the official Microsoft tutorials, is to use ViewBag. ViewBag doesn’t have a direct equivalent in Web Forms, but it’s most closely comparable with Page.Items.

So, in your Details view, if you wanted to display data from two separate Models, you would have something like this:

Next, in your Car Details View (Details.cshtml), you would access the ViewBag to render out your turbo string:

Bear in mind that ViewBag can only be used in a Controller and then displayed in the corresponding View. If you do a redirect, you’ll lose the value stored in the ViewBag.

If you need the data to survive a redirect, use TempData instead. TempData’s equivalent in Web Forms would be a Session variable.

 

This is nothing particularly wrong with using ViewBag and TempData (although the pedants on StackExchange would say otherwise!), but there is another method called ViewModels that has some advantages. I’ll look at ViewModels in my next post.

Feel free to post any questions or comments down below.