2

I have a model which has a string property and a enum property.

I want the label, so DisplayName be different depending on the enum property value eg.

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

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

Is there any way to do it?

tereško
  • 58,060
  • 25
  • 98
  • 150
nickornotto
  • 1,946
  • 4
  • 36
  • 68
  • you could check my answer below. maybe your own attribute could solve the problem. There would be a possibility to extend DisplayName only because Display is sealed – Boris Sokolov Jan 07 '16 at 11:38

1 Answers1

0

It looks like this code would work for const Type only:

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; }
}

There should be possible second option with your own implementation of the 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; }
}

However I don't feel that the both solutions are better then adding some kind of label to your ViewModel

Boris Sokolov
  • 1,723
  • 4
  • 23
  • 38