cant add new custom Model Binder ? error An item w

2019-09-09 17:02发布

问题:

I m trying to add a new custom Model Binder but not successful. Below is my code and in term of basic working (removing formatting and converting 2,345.34 to 234534) it is doing fine:

 public class TransactionModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue("Transaction.Price");
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            object newValue = null;
            try
            {
                if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    newValue = valueResult.AttemptedValue.Replace(",", "");
                }
                actualValue = Convert.ToDecimal(newValue,
                    CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
    }

My Global.asax code is given below:

 protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(decimal), new CurrencyModelBinder());
        ModelBinders.Binders.Add(typeof(decimal), new TxTransactionModelBinder());

        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
       // RouteTable.Routes.MapHubs();


    }

Issue: On running code TransactionModelBinder work fine but in global.asax I got the follwoing error:

An item with the same key has already been added.

I can understand typeof(decimal) in two custom binders is causing this issue.

Can you please guide and help me on how to fix this.

回答1:

You can only have a single model binder per datatype. I'm not entirely sure what the difference is between the two binders, but perhaps you could combine their logic into a single model binder. If you absolutely need two different model binders, then perhaps you need to create two different datatypes specific to each model binder.