MVC 4视图模型验证属性 - 字符串长度 - 错误

时间:2015-08-05 14:09:19

标签: validation asp.net-mvc-5 attributes string-length

我在MVC5 viewmodel上使用StringLength验证属性:

        [Required]
        [StringLength(4, MinimumLength = 4, ErrorMessage = "The postcodes must be 4 characters long.")]
        [Display(Name = "Postcode (four digits)")]
        public int Postcode { get; set; }

客户端验证有效,但是当我通过提交表单执行操作时,我收到此错误:

Unable to cast object of type 'System.Int32' to type 'System.String'. 

我知道这是导致这种情况的属性,因为当我注释掉[StringLength]属性时一切正常。

我怀疑这与属性类型为int的事实有关。但是如何指定整数属性的字符串长度验证?将字符串类型放在ViewModel中,然后在控制器中将其解析为int最佳解决方案,还是有一个属性?在属性驱动的解决方案会很好。

编辑:我尝试了[DataType(DataType.PostalCode)],但它没有用。

感谢。

2 个答案:

答案 0 :(得分:2)

DataType属性不能用于验证用户输入。它们仅提供使用模板化助手渲染值的提示。

该范围是对int的完美验证。

[Required]
[Range(1000,9999, ErrorMessage="The postcodes must be 4 characters long.")]  
[Display(Name = "Postcode (four digits)")]
public int Postcode { get; set; }

答案 1 :(得分:1)

int使用范围,字符串使用字符串长度,不能将字符串长度转换为int。 [DataType(DataType.PostalCode)]只能使用字符串。对于邮政编码,你可以做一些事情。

我建议把它变成一个字符串。

我会用RegularExpression创建一个字符串:

        [Required(ErrorMessage = "Postal Code is Required")]
        [DataType(DataType.PostalCode)]
        [RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Postal Code Invalid.")]
        [Display(Name = "Postcode (four digits)")]
        public string Postcode { get; set; }