Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending more than one model to view MVC 4

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.

like image 692
user1448260 Avatar asked Jul 16 '12 05:07

user1448260


People also ask

Can a controller have multiple views?

Yes You can use multiple View in one Controller.

What is multiple view support in MVC?

ASP.NET MVC supports the ability to define "partial view" templates that can be used to encapsulate view rendering logic for a sub-portion of a page. "Partials" provide a useful way to define view rendering logic once, and then re-use it in multiple places across an application.


2 Answers

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 ;
like image 94
Anand Avatar answered Oct 05 '22 15:10

Anand


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

like image 41
Michael Christensen Avatar answered Oct 05 '22 16:10

Michael Christensen