私がしたことは、データ型を文字列に設定して、maskedinput で動作するようにしましたが、カスタム モデル バインダーで、数値以外のすべての文字を取り除いて、データベースに int として保存できるようにしました。ユーザーはクライアント側の maskedinput によって数字以外の文字を入力できず、サーバー側で不適切な可能性のある文字が除外されるため、クライアント側とサーバー側の両方の保護が得られます。
カスタム モデル バインダー コードは次のとおりです。
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、エディター テンプレート、目立たない検証を使用してすべてを行う方法は次のとおりです。