Skip more than one model to view

public ActionResult Index()
{ 
    var pr = db.products;
    return View(pr); 
}

Firstly - I want to move on to presenting more data - something like:

public ActionResult Index()
{ 
    var pr = db.products;
    var lr = db.linksforproducts(2)
    return View(pr,lr); 
}

How to read data lrin a view?

Secondly - in the view, I have a product table, and I want to add a column to the table with all the tags for these products. How to get tags for each product?

now i am creating this code

public class catnewModel
{

    public IQueryable<category> dl { get; set;   }
    public IQueryable<product> dr { get; set;   }
}

and my controller

public ActionResult Index()
    {

        var pr = db.products;
        var pl = db.categories;

        catnewModel model = new catnewModel();
        model.dr = pr;
        model.dl = pl;

        return View(model);
    }

in my opinion I'm trying to iterate

 <% foreach (var item in Model.dr)  %>

but i get an error on

error CS1061: 'System.Collections.Generic.IEnumerable<amief.Models.catnewModel>' does not contain a definition for 'dr' and no extension method 
+3
source share
3 answers

I did this by creating a ViewModel for the view in which you need information.

Then, within this ViewModel, there are properties to host other models.

Something like that:

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); 
}
+9
source

, :

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

:

public ActionResult Index()
{ 
    var model = new MyViewModel
    {
        Products = db.products,
        Links = db.linksforproducts(2)
    };
    return View(model); 
}
+4

Usually - you create a view model for each view.

In your case, it will 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);
}
+2
source

Source: https://habr.com/ru/post/1771651/


All Articles