3

文字列プロパティと列挙型プロパティを持つモデルがあります。

ラベルが欲しいので、DisplayNameはenumプロパティの値によって異なります。

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

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

それを行う方法はありますか?

4

1 に答える 1

1

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

于 2016-01-07T11:04:40.303 に答える