Sending more than one model to view MVC 4

后端 未结 3 888
一向
一向 2021-02-20 15:46

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 sa

3条回答
  •  野性不改
    2021-02-20 15:54

    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 ;
    

提交回复
热议问题