MVC DataAnnotation DisplayName不适用于虚拟项目

时间:2014-08-31 13:29:54

标签: c# asp.net-mvc entity-framework

我有一个Entity类,其中包含一个虚拟列表,它是指向另一个类的链接:

        public virtual Employee Employee1 { get; set; }

因此,在编辑页面中,当我需要时,我的项目标签为Employee1"我的员工"所以在我的DataAnnotation类中我添加

[DisplayName("My Employee")]
public virtual Employee Employee1 { get; set; }

但它尚未奏效。 DataAnnotation类中的其他项目运行良好。

2 个答案:

答案 0 :(得分:4)

因为visual studio在自动创建视图时没有工作,因为外键使用Labelfor代替DisplaynameFor,如下所示:

            @Html.LabelFor(model => model.Employee1.LastName, "Employee1")

因此,请从第二个参数而不是DataAnnotation读取该值,因此我们需要将其更改为:

           @Html.LabelFor(model => model.Employee1.LastName, "My Employee")

答案 1 :(得分:0)

您需要在原始类属性中提供DataAnnotation。如果将DataAnnotation提供给虚拟属性,则它不起作用。我测试过了。但是如果您将DataAnnotation赋予原始类中的属性。它有效。

如:

public partial class Languages
{
   DataAnnotation  here
    public string Code { get; set; }
    public string Name { get; set; }
}



public partial class Categories
{

    public string Code { get; set; }
    public string FKLanguageCode { get; set; }
    public string Name { get; set; }
    public Nullable<int> Order { get; set; }

     DataAnnotation Not Here
    public virtual Languages Languages { get; set; }
 }
相关问题