Search code examples
c#asp.net-mvcdata-annotationsdisplayname-attribute

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


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?


Solution

  • 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