asp.net-mvc - 如何在 ASP.NET MVC 中显示外键字段的显示名称

标签 asp.net-mvc data-annotations foreign-key-relationship displayname-attribute

我见过很多类似的问题,但似乎没有一个有直接的答案。
当我尝试将 Display(Name) 属性添加到外键字段时,显示名称未显示在创建、编辑、删除和详细信息表单中。
我也尝试将属性放在导航属性上:

[Display(Name="Gender")]
public virtual Gender Gender {get; set;}

但这也不起作用。
public class Person
{
    public int ID {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    [Display(Name="Gender")]
    public int GenderID {get; set;}

    public virtual Gender Gender {get; set;}
}


public class Gender
{
    public int ID {get; set;}
    public string GenderName {get; set;}

    public virtual ICollection<Person> People {get; set;}       
}

最佳答案

解决方法很简单。在模型中添加显示属性后,从 View 中删除标签名称。

所以改变

            @Html.LabelFor(model => model.GenderID, "GenderID", htmlAttributes: new { @class = "control-label col-md-2" })


            @Html.LabelFor(model => model.GenderID, htmlAttributes: new { @class = "control-label col-md-2" })

在你看来。
当您搭建 View 时会出现此问题。

关于asp.net-mvc - 如何在 ASP.NET MVC 中显示外键字段的显示名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704477/

相关文章:

mysql - 为什么要为外键烦恼?

mysql - 我可以向子项添加检查约束以检查其在 MySQL 中的父项的值吗?

c# - 防止 ASP.NET Web API 路由引擎扣除自定义方法名称

asp.net-mvc - 如何将命名空间添加到自定义路由扩展

c# - Web.Config AppSettings 中的 Json

c# - 是否可以将 DataAnnotations 与接口(interface)一起使用?

c# - MVC 中的共享点

entity-framework - 通过 Entity Framework 6.0、Fluent API 和 DataAnnotations 重用所需属性的列

model-view-controller - StringLength 在 MVC4.0 中未按预期工作

NHibernate 多对一映射 : If parent is null, 将外键设置为空 Guid 而不是 null