显示模型中外键属性的显示值

时间:2012-05-11 19:38:57

标签: asp.net-mvc-3 entity-framework

我有一个看起来像这样的模型:

public class Notes
{
public int NoteID {get; set;}
public string Note {get; set;}
public int CustomerID {get; set;}
{

在Notes Details视图中,我希望能够显示Customer Name而不是CustomerID。显然,如果这是一个创建或编辑视图,我使用下拉列表。 但是我不确定如何在只读详细信息视图中显示值而不是ID。

谢谢!

2 个答案:

答案 0 :(得分:8)

Code First主要是......代码,而不是数据库逻辑。

所以,不要在你的模型中使用外键(如CustomerID)(这也是可能的,有时需要,但并非总是如此),你将更容易拥有引用属性

public virtual Customer Customer {get;set;}

因此,在您将Notes作为模型的视图中,您可以简单地使用

@Html.DisplayFor(m => m.Customer.Name);

当您检索Notes实体时,不要忘记包含View / ViewModel所需的相关实体/属性(我让您了解延迟加载)

答案 1 :(得分:0)

您可以尝试以下方法:

var applicationDbContext = _context.Notes.Include(n => n.Custumer);
return View(await applicationDbContext.ToListAsync());

此代码必须在您的控制器中,Index方法中或您命名的任何内容中。 这是可见的。

@Html.DisplayFor(modelItem => item.Customer.Name)