我所做的是将数据类型设置为字符串,以便它可以与 maskedinput 一起使用,但随后在自定义模型绑定器中,我删除了所有非数字字符,以便它可以作为 int 保存到数据库中。您仍然可以获得客户端和服务器端的保护,因为用户被屏蔽输入客户端阻止输入非数字字符,并且潜在的坏字符被过滤掉服务器端。
这是自定义模型绑定器代码:
public class CustomModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if (value != null && propertyDescriptor.PropertyType == typeof(string))
{
// always trim strings to clean up database padding
value = ((string)value).Trim();
if ((string)value == string.Empty)
{
value = null;
}
else if ((propertyDescriptor.Attributes[typeof(PhoneNumberAttribute)] != null
|| propertyDescriptor.Attributes[typeof(ZipCodeAttribute)] != null
|| propertyDescriptor.Attributes[typeof(SocialSecurityNumberAttribute)] != null)
&& bindingContext.ValueProvider.GetValue(propertyDescriptor.Name) != null
&& bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue != null)
{
value =
Regex.Replace(bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue,
"[^0-9]", "");
}
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
自定义属性只是空属性:
public class ZipCodeAttribute : Attribute { }
在视图模型中,只需像这样标记您的字段:
[ZipCode]
public string Zip { get; set; }
以下是如何使用 maskedinput、编辑器模板和不显眼的验证来完成整个事情。