基本的MVC可空字符验证

时间:2016-10-19 10:21:20

标签: validation asp.net-mvc-4 attributes

我的一个视图模型中有以下内容:

public char? MyChar { get; set }

我注意到MyChar的文本框上似乎没有客户端验证,并且用户可能会向我的控制器提交一个太短的字符串char只是不绑定并保持为null)。

所以,我添加了[MaxLength]注释。客户端验证现在按预期工作,但是当我向服务器提交有效值时,我在事件日志中得到以下异常:

Exception information: 
    Exception type: InvalidCastException 
    Exception message: Unable to cast object of type 'System.Char' to type 'System.Array'.
   at System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(Object value)

如何在客户端和服务器端正确验证char的最大长度?

我尝试过什么

目前,我已经创建了自己的MaxLength属性,以便与char类型一起使用,但这感觉就像一个沉重的方法。

0 个答案:

没有答案