ASP.NET MVCで入力値の自動補正を行いたい場合、どこに処理を入れるのが適切かしらん(・ω・)?
Webアプリで、入力値の自動補正を行いたい事がありますが。
入力値の前後のスペースをトリムしたりとか。
あるいは、全角/半角の入力をヴァリデーションでエラーにするのではなくて、かなカナ全角半角変換を自動で行ってしまうだとか。
PHPやJavaの我々フレームワークにもこの自動補正機能を入れてあるんですが、ASP.NET MVCでやりたい場合にはどこに処理を入れるべきか(・ω・)?
まあ、個別のIModelBinderを用意したり、ViewModelクラスのプロパティに小細工を入れれば、一応補正はできますが…。
でも、そんな個別の処理を書くのは面倒なので、補正の指定方法としては、こんな風に属性を使うとして(・ω・)
public class UserViewModel { [CorrectTrim] public string LastName { get; set; } [CorrectTrim] public string FirstName { get; set; } }
あと、ASP.NET MVCの場合、ValueProviderResultも更新したいわけで。*1
っで、とりあえず今は、DefaultModelBinder派生のカスタムModelBinderでBindProperty()をoverrideして、DefaultModelBinder.BindProperty()で言うところの、下記の箇所で補正処理を行っているんですが。
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) { ... // ここでbindingContext.Model.GetType()、propertyDescriptor.Nameに対応する // 補正処理(ValueProviderResultの更新)を実行 object newPropertyValue = propertyBinder.BindModel( controllerContext, innerBindingContext ); if( OnPropertyValidating( controllerContext, bindingContext, propertyDescriptor, newPropertyValue ) ) { SetProperty( controllerContext, bindingContext, propertyDescriptor, newPropertyValue ); OnPropertyValidated( controllerContext, bindingContext, propertyDescriptor, newPropertyValue ); } }
この方法だと、補正の対象はViewModelクラスのメンバ限定で、アクションメソッドの引数に個別に指定したパラメータの補正はできなかったりしますが(´д`;)
まあ、色々対応しようとすると、ParameterBindingInfoやIActionInvokerのあたりの処理も用意しなければいけない気がして、とりあえず上記の対応だけに止めているんですが。
どこで処理を入れるのが適切なんだろうね〜(´ω`)?
ところで、最近になってASP.NET MVCもじわじわと来ている気がする(・∀・)
*1:ValueProviderResultが以外と邪魔くさく感じることもある(´д`;)