[英]System.ComponentModel.DataAnnotations attribute not recognized. Unable to use StringLength attibute to verify empty string
[英]Can I use other attribute arguments than numbers in DataAnnotations.StringLength?
我有一個包含所有硬編碼代碼的 (Settings) 類。 它對於某些字段(例如 maxCharactersFields 和錯誤消息)非常方便,這樣我就可以將相同的字段用於映射、模型和視圖模型。 因此,如果它在未來改變它,一切都會以同樣的方式改變。 但是,我似乎無法在視圖模型中使用它。 更具體地說,在 System.ComponentModel.DataAnnotations 的 StringLength 中。
它給出的錯誤是“屬性參數必須是屬性參數類型的常量表達式、typeof 表達式或數組創建表達式。”
我已經嘗試過的某些事情是用我正在工作的 ViewModel 中的一個字段替換它,但它給出了相同的錯誤。 我在 StackOverflow 上用谷歌搜索並搜索過,但似乎找不到任何試圖做這樣的事情並遇到同樣問題的人。
到目前為止我學到的是我不能使用我的 Settings 類,因為它不是一個基本類型但是有沒有辦法解決它?
錯誤發生在 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
....
}
它實際上與您的設置類類型無關。 屬性是編譯時的東西,所以你不能使用靜態或實例值。 您必須使用常量值( public const int
):
public static class Settings
{
public const int maxCharactersEmail= 320; //Googled it
}
您的屬性現在將起作用:
[Display (Name = "E-mail van de gebruiker", Prompt = "John.Doe@gmail.com")]
[DataType (DataType.EmailAddress)]
[Required]
[StringLength(Settings.maxCharactersEmail)]
public string Email { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.