4

すべてのモデルのすべての文字列プロパティにブランケットを適用したいという一般的な検証があります。メソッドをオーバーライドして、をサブクラス化し、DefaultModelBinderロジックを追加することを検討していBindPropertyます。これは適切なことでしょうか?

4

2 に答える 2

2
  1. 独自のカスタム モデル バインダーを記述します。
  2. Reflection を使用してすべてのプロパティを取得する
  3. プロパティが次のタイプかどうかを確認しますstring
  4. リフレクションを使用してプロパティの値を取得する
  5. カスタム検証を実行し、検証エラーをModelState

サンプル

public class MyCustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        foreach (var propertyInfo in typeof(bindingContext.Model.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
        {
           if (propertyInfo.PropertyType == typeof(string)) 
           {
               var value = propertyInfo.GetValue(bindingContext.Model);
               // validate
               // append to ModelState if validation failed
               bindingContext.ModelState.AddModelError(propertyInfo.Name, "Validation Failed");
           }
        }
    }
}

ModelBinder を使用する

public ActionResult MyActionMethod([ModelBinder(typeof(MyCustomModelBinder ))] ModelType model)
{
  // ModelState.IsValid is false if validation fails
}

詳しくは

于 2012-10-09T13:59:05.073 に答える
1

のサブクラス化DefaultModelBinderとオーバーライドBindPropertyは、私にとってはうまく機能しています。base.BindProperty を呼び出すと、モデルのプロパティが確実に設定され、グローバル検証のために評価できます。

于 2012-10-10T15:51:27.770 に答える