I want to use a 'static readonly' field from a Settings class, this is where all my hardcoded code is, such as error messages and constants, in a [StringLength] attribute for a ViewModel. However, StringLength, does not accept attribute arguments that aren't constant expression, typeof expression or array expressions. However the field I use cannot be changed to a constant expression because it uses other constant fields and thus gives an error.
I know there's a way around this by using the string and constant expression
The reason why I want this is because it will make things very easy changable in the future if I were to change some hardcoded code. The hardcoded code is used in multiple locations such as model classes and view models, since they have the same requirements.
I tried using a property getter for this field that is a constant but that doesn't seem to work either. I've googled and looked here on stackoverflow, but can't quite seem to find anyone with the exact same issue.
I also tried using a string.Format() as argument, althought this is NOT the solution I want because then I still have to change this message in multiple locations.
The error occurs for Settings.LastNameLength in the line of StringLength.
public class DeelnemerViewModels
{
...
[Display (Name = "Lastname", Prompt = "Doe")]
[Required (ErrorMessage = Settings.fieldNeeded)]
[StringLength (Settings.maxAmountOfCharactersLastName, MinimumLength = Settings.minAmountOfCharactersLastname, ErrorMessage = Settings.LastNameLength)]
public string Lastname { get; set; }
...
}
public static class Settings
{
...
public const int minAmountOfCharactersLastname = 2;
public const int maxAmountOfCharactersLastName = 50;
public static readonly string LastNameLength =
"The lastname does not fit the requirements. The lastname must atleast be "
+ minAmountOfCharactersLastname + " characters long and at max "
+ maxAmountOfCharactersLastName + " characters long.";
...
}