Pass more than one model to view

后端 未结 3 771
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 07:48
public ActionResult Index()
{ 
    var pr = db.products;
    return View(pr); 
}

Firstly - I want to pass to the view more data - something like:

相关标签:
3条回答
  • 2021-01-14 08:08

    Create a view model containing two properties:

    public class MyViewModel
    {
        public IEnumerable<Product> Products { get; set; }
        public IEnumerable<LinkProduct> Links { get; set; }
    }
    

    And in your controller:

    public ActionResult Index()
    { 
        var model = new MyViewModel
        {
            Products = db.products,
            Links = db.linksforproducts(2)
        };
        return View(model); 
    }
    
    0 讨论(0)
  • 2021-01-14 08:14

    Usually - You create view model per view.

    In Your case, that would be:

    public class IndexModel{
      public ProductModel[] Products{get;set;}
      public LinkForProduct[] Links{get;set;}
    }
    
    public ActionResult Index(){
      var model=new IndexModel{
        Products=Map(db.products), 
        Links=Map(db.linksforproducts(2)};
      return View(model);
    }
    
    0 讨论(0)
  • 2021-01-14 08:24

    I have done this by making a ViewModel specific to the view you need the information in.

    Then within that ViewModel just have properties to house your other models.

    Something like this:

    public class ViewModel
    {
        public List<ProductModel> Products(){get; set;}
        public List<LinksForProductModel> LinksForProducts(){get; set;}
    }
    
    
    public ActionResult Index()
    { 
        var pr = db.products;
        var lr = db.linksforproducts(2)
    
        ViewModel model = new ViewModel();
        model.Products = pr;
        model.LinksForProducts = lr;
    
    
        return View(model); 
    }
    
    0 讨论(0)
提交回复
热议问题