I have one Parent table and its child table.I have to display title from parent and child table on page as given below in MVC project:
Assume that parent is User
and Product
is their childs. Here is your entities.
public class User {
public int Id {get; set;}
public string Name {get; set;}
}
public class Product {
public int Id {get; set;}
public string Name {get; set;}
//user who created this product
public int UserId {get; set;}
}
You can create viewmodel and collect your data to show:
public class ProductUserViewModel {
public User User {get; set;}
public List Products {get; set;}
}
In action collect data:
public ActionResult GetAllUsersAndTheirProducts()
{
var allUsers = db.UserTable.ToList();
List result = new List();
foreach(var user in allUsers)
{
ProductUserViewModel model = new ProductUserViewModel();
model.User = user;
model.Products = db.ProductTable.Where(e=>e.UserId == user.Id).ToList();
result.Add(model);
}
return View(result);
}
And In view:
@model IEnumerable
foreach(var item in Model)
{
- @item.User.Name
foreach(var product in item.Products)
{
- @product.Name
}
}