我的模型:
public virtual int? NumberTest { get; set; }
我的观点
@Html.LabelFor(model => model.NumberTest)
<br />
@Html.TextBoxFor(model => model.NumberTest)
我正在使用Masked Input Plugin ,所以我的 View 中有:
$("#NumberTest").mask("99999-999");
我生成的 Html :
<input data-val="true" data-val-number="The field NumberTest must be a number." id="NumberTest" name="NumberTest" type="text" value="" />
因此它会自动对我的整数输入生成数字验证...并且我使用带有非整数字符的掩码来格式化数字...
当我填写输入时,总是会调用此验证器...我该如何解决这个问题?
最佳答案
我所做的是将数据类型设置为字符串,以便它可以与 maskedinput 一起使用,但随后在自定义模型绑定(bind)器中,我删除了所有非数字字符,以便它可以作为 int 保存到数据库中。您仍然可以获得客户端和服务器端保护,因为客户端的 maskedinput 会阻止用户输入非数字字符,并且服务器端会过滤掉潜在的错误字符。
这是自定义模型绑定(bind)器代码:
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 { }
在 View 模型中,只需像这样标记您的字段:
[ZipCode]
public string Zip { get; set; }
以下是如何执行 whole thing with maskedinput, editor templates and unobtrusive validation .
关于asp.net-mvc-3 - 使用掩码验证整数输入 (Asp .NET MVC 3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6472098/