すべてのモデルのすべての文字列プロパティにブランケットを適用したいという一般的な検証があります。メソッドをオーバーライドして、をサブクラス化し、DefaultModelBinder
ロジックを追加することを検討していBindProperty
ます。これは適切なことでしょうか?
質問する
902 次
2 に答える
2
- 独自のカスタム モデル バインダーを記述します。
- Reflection を使用してすべてのプロパティを取得する
- プロパティが次のタイプかどうかを確認します
string
- リフレクションを使用してプロパティの値を取得する
- カスタム検証を実行し、検証エラーを
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 に答える