[英]How to MVC C# Viewmodel to join data from multiple tables
Can anyone please tell me, I need to MVC C# Viewmodel join data from multiple tables and use chtml page @model ViewModels.StoreBrowseViewModel.谁能告诉我,我需要 MVC C# Viewmodel 连接来自多个表的数据并使用 chtml 页面 @model ViewModels.StoreBrowseViewModel。 But my logic will retrieve only one table data.
但是我的逻辑只会检索一个表数据。 This is my class diagram.
这是我的类图。 red box primary key, blue box foreign key
红框主键,蓝框外键
This is my StoreBrowseViewModel class这是我的 StoreBrowseViewModel 类
public class StoreBrowseViewModel
{
public int Id { get; set; }
public string Shape { get; set; }
public string Name { get; set; }
public string Clarity { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
public Shape Shapes { get; set; }
public IEnumerable<Gemstone> Gemstones { get; set; }
public IEnumerable<Clarity> Clarites { get; set; }
}
This is my action method.这是我的行动方法。
public ActionResult Browse(string gemCategory = "")
{
var gemstones = from g in db.Gemstones
select g;
var category = db.Categories.Where(p => p.Name == gemCategory).FirstOrDefault();
gemstones = (gemstones.Include(s => s.Shapes)
.Include(c => c.Clarities)
.Where(p => p.CategoryID == category.CategoryID));
var viewModel = new StoreBrowseViewModel()
{
Category = category,
Gemstones = gemstones,
};
return this.View(viewModel);
}
This is my view model chtml page这是我的视图模型 chtml 页面
@model ViewModels.StoreBrowseViewModel
grid.Column("Carat", header: "Weight " + Html.SortDirection(ref grid, "Carat")@item.Carat),
grid.Column("ShapeId", header: "Shape " + Html.SortDirection(ref grid, "Shape")@item.Shape),
grid.Column("ClarityId", header: "Clarity " + Html.SortDirection(ref grid, "Clarity")@item.Clarity),
grid.Column("Price", header: "Price(USD) " + Html.SortDirection(ref grid, "Price")@item.Price),
This is my out put It should display shape name and clarity name这是我的输出 它应该显示形状名称和清晰度名称
I would do it differently from what im gona show below but this should help...我的做法与我将在下面展示的有所不同,但这应该会有所帮助...
public ActionResult Browse(string gemCategory = "")
{
var category = db.Categories.FirstOrDefault(p => p.Name == gemCategory);
var gemstones = db.Gemstones.Include(s => s.Shapes)
.Include(c => c.Clarities)
.Include(c => c.Categories)
.Include(c => c.Cuts)
.Include(c => c.Orgins)
.Where(p => p.CategoryID == category.CategoryID);
var viewModel = new StoreBrowseViewModel() {Gemstones = gemstones};
return View(viewModel);
}
view model视图模型
public class StoreBrowseViewModel
{
public IEnumerable<Gemstone> Gemstones { get; set; }
}
in the view在视图中
@foreach(var item in Model.Gemstones)
{
<span>@item.Name</span>
@foreach(var item2 in Model.Gemstones.Clarities)
{
<span>@item2.Name</span>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.