我第一次在這裏,我希望這有助於: 比如產品型號爲:
[Table("Products")]
public class Product
{
[Key]
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
分類模型:
[Table("Categories")]
public class Category
{
[Key]
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
產品類別mo德爾:
[Table("ProductCategories")]
public class ProductCategory
{
[Key]
[Column(Order = 0)]
public string ProductId { get; set; }
[Key]
[Column(Order = 1)]
public string CategoryId { get; set; }
public virtual Category Category { get; set; }
}
您需要添加視圖模型:
// GET: Products/Details/5
public async Task<ActionResult> Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = await db.Products.FindAsync(id);
if (product == null)
{
return HttpNotFound();
}
ProductDetailsViewModel model = new ProductDetailsViewModel()
{
Product = await db.Products.SingleOrDefaultAsync(x => x.Id == id),
ProductCategories = await db.ProductCategories.Where(x => x.ProductId == id).ToListAsync()
};
return View(model);
}
所以finaly詳情查看:
@model YourApplicationName.Models.ProductDetailsViewModel
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Product.AddedAt)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.AddedAt)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.Description)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.InwearhouseQuantity)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.InwearhouseQuantity)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.InternalPrice)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.InternalPrice)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.ExternalPrice)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.ExternalPrice)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.Published)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.Published)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Product.Url)
</dt>
<dd>
@Html.DisplayFor(model => model.Product.Url)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ProductCategories)
</dt>
<dd>
<table class="table">
<tr>
<th>Category</th>
<th>Description</th>
</tr>
@foreach (var item in Model.ProductCategories)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Category.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Category.Url)
</td>
</tr>
}
</table>
</dd>
</dl>
public class ProductDetailsViewModel
{
public virtual Product Product { get; set; }
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
控制器的 「詳細信息」 部分現在例子
我會試着看看這是否會幫助我。 – Barrosy