Linq Join Query - 如何在视图中显示新表MVC C#

2D3*_*D3D 2 html c# linq asp.net-mvc-4

我在linq中进行了一个查询,加入了2个类,问题是我现在要在视图中显示它,因为查询在控制器中这里是查询:

 public ActionResult JoinSupToPro()
    {
        SupplierDBContext dbS = new SupplierDBContext();
        var innerJoinQuery = from pro in db.Products join sup in dbS.Suppliers on pro.SupplierId equals sup.ID
        select new { pro.Name,pro.Price,  NameSup= sup.Name , sup.Phone,};

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

我如何在视图中显示它们?

Gur*_*Rao 6

我建议创建一个新的viewmodel类来加载来自2个不同表的数据,如下所示:

public class ProductSupplier
{
    public string ProName {get; set;}
    public string Price{get; set;}
    public string SupName{get; set;}
    public string SupPhone{get; set;}
}
Run Code Online (Sandbox Code Playgroud)

现在,当您从中controller填写数据model并将其返回到视图时,如下所示:

public ActionResult JoinSupToPro()
{
    SupplierDBContext dbS = new SupplierDBContext();
    //Create list instance of your model
    List<ProductSupplier> model=new List<ProductSupplier>();
    var innerJoinQuery = (from pro in dbs.Products 
                         join sup in dbS.Suppliers 
                         on pro.SupplierId equals sup.ID
                         select new 
                         { 
                             proName=pro.Name,
                             proPrice=pro.Price,  
                             supName= sup.Name , 
                             supPhone=sup.Phone
                         }).ToList();//convert to List
    foreach(var item in innerJoinQuery) //retrieve each item and assign to model
    {
          model.Add(new ProductSupplier()
          {
                ProName = item.proName,
                Price = item.proPrice,
                SupName = item.supName,
                SupPhone = item.supPhone
          });
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

从控制器传递模型后,您可以在视图中显示它,如下所示:

//Refer the list instance of model in your view
@model IEnumerable<ProjectName.Models.ProductSupplier>
@foreach(var item in Model)
{
      //assign this values to any element of html
      //by referring it as @item.ProName, @item.Price etc.,
}
Run Code Online (Sandbox Code Playgroud)

希望很清楚