10

I have two model classes, each is a table in a database. One model is called 'Clothes' and the other 'Shoes'.

I want to display the contents of each table in the same razor view, but MVC is only letting me send one model to the view.

@model IEnumerable<Test.Models.Clothes>

Is there a way to send more than one model to a razor view?

If not, what is the normal way to display contents of another model in a view that has already got another model passed to it. Thanks for advice.

user1448260
  • 263
  • 1
  • 7
  • 16

3 Answers3

12

Either make a view model class which has both the class as its object. It would be then type safe.

public class ViewModelForDisplay
{
       public Clothes Clothes {get; set;}
       public Shoes Shoes {get; set;}
}

//on Controller
Clothes objClothes = GetClothes();
Shoes objShoes = GetShoes();

ViewModelForDisplay objViewModel = new ViewModelForDisplay() {Clothes = objClothes, Shoes= objShoes }

The other easy way to do it by using ViewBag.It uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. Its also Type Safe

ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;

You could also use ViewData to pass objects to html. BUt this would not be type safe. It requires casting

ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;
Anand
  • 14,545
  • 8
  • 32
  • 44
2

Make your own class aka View Model and have it composed of both models.

Michael Christensen
  • 1,768
  • 1
  • 13
  • 11
0

I have found this article very interesting :

https://workspaces.codeproject.com/user-10826818/using-multiple-models-in-a-view-in-asp-net-mvc-4

It presents different ways to send multiple models to a view :

  • ViewData
  • ViewBag
  • PartialView
  • TempData
  • ViewModel
  • Tuple
Rabskatran
  • 2,269
  • 5
  • 27
  • 41