【发布时间】:2016-12-24 15:20:19
【问题描述】:
ItemCategory 类:
public class ItemCategory
{
[Key]
public int CategoryId { get; set; }
[Required]
[Display(Name ="Category Name")]
public string CategoryName { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
Item 类如下:
public class Item
{
[Key]
public int ItemId { get; set; }
[Required]
[Display(Name = "Item Name")]
public string ItemName { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[DataType(DataType.Text)]
[Display(Name ="Category Code")]
public int CategoryId { get; set; }
public ItemCategory ItemCategory { get; set; }
[NotMapped]
public string CategoryName { get; set; }
}
这是项目控制器的代码:
// GET: Items/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var items = db.Items.Include(i => i.ItemCategory);
if (items == null)
{
return HttpNotFound();
}
//var thisItem = db.Items.FirstOrDefault(item => item.ItemId == id);
return View(await db.Items.FindAsync(id));
}
查看代码如下:
@model ContactManager.Models.Item
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.ItemCategory.CategoryName)
</dt>
<dd>
@Html.DisplayFor(model => model.ItemCategory.CategoryName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ItemCode)
</dt>
<dd>
@Html.DisplayFor(model => model.ItemCode)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ItemName)
</dt>
<dd>
@Html.DisplayFor(model => model.ItemName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Price)
</dt>
<dd>
@Html.DisplayFor(model => model.Price)
</dd>
<dt>
@Html.DisplayNameFor(model => model.BarCode)
</dt>
<dd>
@Html.DisplayFor(model => model.BarCode)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ItemId }) |
@Html.ActionLink("Back to List", "Index")
</p>
我是 ASP.NET MVC 和实体框架的新手。当我执行代码时,视图不会在此视图中显示类别名称,我真的很想知道如何在此视图中获取类别名称....谢谢
【问题讨论】:
标签: asp.net asp.net-mvc entity-framework model-view-controller