Reputation: 353
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?
Upvotes: 2
Views: 16253
Reputation: 29683
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
Upvotes: 7
Reputation: 148
You Need to Pass data to view. like
return view(innerJoinQuery.ToList())
Please Refer this link for Details
Upvotes: 0
Reputation: 10919
You have two options here, one use Ajax to display this query in the view. Useful, but you may need to create html dynamically, depends on what you want to achieve.
The second one is to use view model and to call this model in your view, so will be able to achieve the following:
foreach(var item in model)
{
<td>item.prop<td>
}
Good Luck!
Upvotes: 0