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.