Can I use other attribute arguments than numbers in DataAnnotations.StringLength?

房东的猫 提交于 2019-12-11 10:17:01

问题


I have a (Settings) class that contains all hardcoded code. It's really handy for certain fields such as maxCharactersFields and error messages, this way I can use the same field for mapping, models & viewmodels. Therefore if it were to change it the future, everything changes the same way. However, I cannot seem to use this in viewmodels. More specifically in StringLength of System.ComponentModel.DataAnnotations.

The error it gives is "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type."

Certain things that I've already tried is replacing it with a field in the ViewModel in which I'm working, but it gives the same error. I've googled and searched on StackOverflow but can't seem to find anyone who tried to do something like this and ran into the same problem.

What I've learned so far is that I can't use my Settings class because it's not a basic type but is there a way around it?

The error occurs in the line of StringLength.

[Display (Name = "E-mail van de gebruiker", Prompt = "John.Doe@gmail.com")]
        [DataType (DataType.EmailAddress)]
        [Required]
        [StringLength(Settings.maxCharactersEmail)]
        public string Email { get; set; }
    public static class Settings
    {
....
        public static readonly int maxCharactersEmail= 320; //Googled it
....
    }


回答1:


It doesn't actually have anything to do your settings class type. Attributes are a compile-time thing, so you can't use static or instance values. You have to use constant values (public const int):

public static class Settings
{
    public const int maxCharactersEmail= 320; //Googled it
}

Your attribute will now work:

[Display (Name = "E-mail van de gebruiker", Prompt = "John.Doe@gmail.com")]
[DataType (DataType.EmailAddress)]
[Required]
[StringLength(Settings.maxCharactersEmail)]
public string Email { get; set; }


来源:https://stackoverflow.com/questions/55742092/can-i-use-other-attribute-arguments-than-numbers-in-dataannotations-stringlength

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!