2015-07-19 48 views
2

的ViewModels如何驗證詞典中MVC5

[Display(Name = "Purchase limit")] 
[Required] 
public Dictionary<int, int> DownloadLimit { get; set; } 

查看

@foreach (var downloadLimit in Model.DownloadLimit) 
{ 
    @Html.TextBoxFor(m => m.DownloadLimit[downloadLimit.Key], new { @class = "form-control mb10", @type = "number"}) 
} 

我的字典具有鍵和值都爲整數。當我輸入一個字符串到文本框時,顯示消息錯誤:「Int32字段必須是數字」。

  1. 我怎麼能自定義此消息爲「下載限制必須是一個數字」
  2. 我怎麼能添加RangeAttribute驗證所有的值必須在特定的範圍內。

RangeAttribute在Dictionary中不起作用。 我曾嘗試:

[Range(0,99999999, ErrorMessage = "Download Limit must be a number in range from 0 to 99999999")] 
public Dictionary<int, int> DownloadLimit { get; set; } 

任何人都可以建議我這樣做的方式,我非常欣賞到不使用自定義屬性的解決方案。

謝謝!

回答

4
[Range(typeof(int), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")] 

[Range(typeof(decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")] 
+0

感謝@Saravanan!在許多研究中,我發現最好的解決方案是使用自定義註釋來驗證ViewModel上的Dictionary。感謝您的推薦。 –

+0

這是我的榮幸@Vu –