2

我的模型:

public virtual int? NumberTest { get; set; }

我的观点

@Html.LabelFor(model => model.NumberTest)
<br />
@Html.TextBoxFor(model => model.NumberTest)

我正在使用Masked Input Plugin,所以我的视图中有:

$("#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="" />

所以它会在我的整数输入上自动生成一个数字验证......而且我正在使用带有非整数字符的掩码来格式化数字......

当我填写输入时,总是会调用这个验证器......我该如何解决这个问题?

4

1 回答 1

4

我所做的是将数据类型设置为字符串,以便它可以与 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、编辑器模板和不显眼的验证来完成整个事情

于 2011-08-03T19:16:24.257 回答