如何在MVC5中验证字典

时间:2015-07-19 05:50:21

标签: c# asp.net asp.net-mvc-5

的ViewModels

[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以验证所有值必须在特定范围内。
  3. 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; }
    

    任何人都可以建议我这样做,我非常喜欢不使用自定义属性的解决方案。

    谢谢!

1 个答案:

答案 0 :(得分: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}.")]