任何人都可以告诉我,我需要MVC C#Viewmodel从多个表连接数据并使用chtml页面@model ViewModels.StoreBrowseViewModel。但我的逻辑只会检索一个表数据。 这是我的班级图。红框主键,蓝框外键
这是我的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; }
}
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; }
}
这是我的行动方法。
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);
}
这是我的视图模型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),
这是我的输出它应该显示形状名称和清晰度名称
答案 0 :(得分:1)
我会采用与以下内容有所不同的方式,但这应该有所帮助......
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);
}
查看模型
public class StoreBrowseViewModel
{
public IEnumerable<Gemstone> Gemstones { get; set; }
}
视图中的
@foreach(var item in Model.Gemstones)
{
<span>@item.Name</span>
@foreach(var item2 in Model.Gemstones.Clarities)
{
<span>@item2.Name</span>
}
}