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

128 Views Asked by At

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 = "[email protected]")]
        [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

There are 1 best solutions below

2
On

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 = "[email protected]")]
[DataType (DataType.EmailAddress)]
[Required]
[StringLength(Settings.maxCharactersEmail)]
public string Email { get; set; }