【发布时间】:2015-10-29 13:14:24
【问题描述】:
我正在尝试在视图中列出单个产品的详细信息。产品规格会动态变化,因为规格是在表格中逐行添加的,这意味着我们可以为每个产品添加大量规格(就像在电子商务网站中所做的那样)。现在我可以使用ViewBag 满足要求,但我决定使用ViewModel 作为更好的做法。
模型类:
// Product:
public partial class ProductTable
{
public ProductTable()
{
this.SpecificationsTable = new HashSet<SpecificationsTable>();
}
public int ProductID { get; set; }
public string Title { get; set; }
public string SmallDescription { get; set; }
public string FullDescription { get; set; }
public virtual ICollection<SpecificationsTable> SpecificationsTable { get; set; }
}
//Specifications:
public partial class SpecificationsTable
{
public int SpecificationsID { get; set; }
public string SpecificationName { get; set; }
public string SpecificationValue { get; set; }
public Nullable<int> ProductID { get; set; }
public virtual ProductTable ProductTable { get; set; }
}
视图模型:
public class DetailsViewModel
{
public int ProductID { get; set; }
public string Title { get; set; }
public string SmallDescription { get; set; }
public string FullDescription { get; set; }
public string SpecificationName { get; set; }
public string SpecificationValue { get; set; }
}
动作方法
public ActionResult ProductDetails(int id)
{
var details = (from c in dbo.ProductTable
join s in dbo.SpecificationsTable
on c.ProductID equals s.ProductID
where c.ProductID == id
select new DetailViewModel
{
Title = c.Title,
SmallDescription = c.SmallDescription,
FullDescription = c.FullDescription
}).ToList();
// To remove repeated product title , small and full description
var distinctItems = details.GroupBy(x => x.ProductID).Select(y => y.First());
// To show product title, small and full description for this product
ViewBag.ProductDetails = distinctItems;
var specifications = (from c in dbo.ProductTable
join s in dbo.SpecificationsTable
on c.ProductID equals s.ProductID
where c.ProductID == id
select new DetailViewModel
{
SpecificationName = s.SpecificationName,
SpecificationValue = s.SpecificationValue
}).ToList();
// To show list of specifications for this product
ViewBag.Specifcations = specifications;
return View();
}
预期输出:
详情:
Title: New Samsung offer
SmallDescription : Something small
FullDescription : Something full
规格:
Mobile Name :Samsung
Model : 2015
Price : 70 $
Color: White
我正在使用数据库优先方法,我正在尝试在这里学习如何使用视图模型。
【问题讨论】:
-
有点不清楚你在问什么。您有一个不代表您想要显示的视图模型。它需要属性
Title、SmallDescription、FullDescription和IEnumerable<SpecificationViewModel>,其中SpecificationViewModel包含属性SpecificationName和SpecificationValue -
是的,我明白你想做什么。我要说的是您的视图模型是错误的(您对填充它的查询也是如此)。给我 30 分钟,我会添加一个答案,说明你需要做什么。
-
@StephenMuecke,是的,谢谢。
标签: asp.net-mvc asp.net-mvc-4 viewmodel asp.net-mvc-viewmodel