Linq Join Query - How to display new table in view MVC C#
15,255
I would suggest to create a new viewmodel
Class to load data from 2 different tables like one below:
public class ProductSupplier
{
public string ProName {get; set;}
public string Price{get; set;}
public string SupName{get; set;}
public string SupPhone{get; set;}
}
Now when returning data from your controller
you fill the model
and return it to view as below:
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);
}
Once model is passed from controller you can display it in view as below:
//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.,
}
Hope it's clear
Author by
2D3D
By Night: NA NA NA Batman By Day : writing code for my degree
Updated on June 04, 2022Comments
-
2D3D almost 2 years
I made a query in linq to join 2 classes the problem is now i want to show it in the view because the query was in the controller here is the query:
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(); }
How do i show them now in th view?