2

私のモデル:

public virtual int? NumberTest { get; set; }

私の見解

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

私はマスクされた入力プラグインを使用しているので、ビューにあります:

$("#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 として保存できるようにしました。ユーザーはクライアント側の 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、エディター テンプレート、目立たない検証を使用してすべてを行う方法は次のとおりです。

于 2011-08-03T19:16:24.257 に答える