简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM