2

これが必要な理由: コントローラーの 1 つで、アプリケーションの残りの部分とは異なる方法ですべての Decimal 値をバインドしたい。Model Binder を Global.asax に登録したくない (経由ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());)

DefaultModelBinderクラスから派生させてそのBindPropertyメソッドをオーバーライドしようとしましたが、それはモデル インスタンスの直接の (ネストされていない) Decimal プロパティに対してのみ機能します。

私の問題を示すために、次の例があります。

namespace ModelBinderTest.Controllers
{
    public class Model
    {
        public decimal Decimal { get; set; }
        public DecimalContainer DecimalContainer { get; set; }
    }

    public class DecimalContainer
    {
        public decimal DecimalNested { get; set; }
    }

    public class DecimalModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.PropertyType == typeof (decimal))
            {                
                propertyDescriptor.SetValue(bindingContext.Model,  999M);
                return;
            }

            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }

    public class TestController : Controller
    {

        public ActionResult Index()
        {
            Model model = new Model();
            return View(model);
        }

        [HttpPost]
        public ActionResult Index([ModelBinder(typeof(DecimalModelBinder))] Model model)
        {
            return View(model);
        }

    }
}

このソリューションはModelのプロパティを 999 に設定するだけで、のDecimalプロパティには何もしません。これは、のオーバーライドでが呼び出されたためだと認識していますが、10 進数のプロパティを処理するときにモデル バインダーを使用するように基本クラスを説得する方法がわかりません。DecimalContainerDecimalNestedbase.BindPropertyDecimalModelBinderBindProperty

4

1 に答える 1