mvc DisplayName 或 Display(Name=...) 取决于另一个模型 属性

mvc DisplayName or Display(Name=...) depending on another model property

我有一个模型,它有一个字符串 属性 和一个枚举 属性。

我想要标签,因此 DisplayName 会因枚举 属性 值而有所不同,例如

public class DisplayItRight
{
    public TypeEnum Type { get; set; }

    DisplayName(Type == TypeEnum.Apple ? "Good" : "Bad")
    public string GotIt { get; set;}
}

有什么办法吗?

看起来这段代码只适用于 const 类型:

public enum MyEnum
{
    First,
    Second
}

public class LoginViewModel
{

    const MyEnum En = MyEnum.First;

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = (En == MyEnum.First ? "Password" : "aaa"))]
    public string Password { get; set; }
}

您自己实现的 DisplayName 应该有第二个选项:

public enum MyEnum
{
    First,
    Second
}

public MyDisplayNameAttribute : DisplayNameAttribute
{
    public MyDisplayNameAttribute (MyEnum en, string text1, string text2) : base (CorrectName (en, text1, text2))
    {}

    public static string CorrectName (MyEnum en, string text1, string text2)
    {
        return en == MyEnum.First ? text1 : text2;
    }
} 

public class LoginViewModel
{

    const MyEnum En = MyEnum.First;

    [Required]
    [DataType(DataType.Password)]
    [MyDisplayName(MyEnum.Second, "password1", "password2")]
    public string Password { get; set; }
}

但是我不认为这两种解决方案都比向您的 ViewModel 添加某种标签更好