You can correctly apply model binding in your Application_Start :
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
and then have a custom authorization filter (yes, an authorization filter that is executed before the model is bound), which will enter some value into the HttpContext that can later be used by the modelβs middleware:
[AttributeUsage(AttributeTargets.Method)] public class MyDecimalBinderAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { filterContext.HttpContext.Items["_apply_decimal_binder_"] = true; } }
and then in a test binder test if the HttpContext contains a custom value using it:
public class DecimalModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext.HttpContext.Items.Contains("_apply_decimal_binder_")) {
Now all that remains is to decorate the action of your controller with a special filter to enable the decimal binder:
[HttpPost] [MyDecimalBinder] public ActionResult Index(Model model) { return View(model); }
source share