【问题标题】:cant add new custom Model Binder ? error An item with the same key has already been added无法添加新的自定义模型绑定器?错误已添加具有相同密钥的项目
【发布时间】:2014-03-10 04:16:09
【问题描述】:

我正在尝试添加一个新的自定义模型绑定器,但没有成功。下面是我的代码,就基本工作而言(删除格式并将 2,345.34 转换为 234534)它做得很好:

 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;
        }
    }

我的 Global.asax 代码如下:

 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();


    }

问题: 在运行代码 TransactionModelBinder 工作正常但在 global.asax 中我得到了以下错误:

已添加具有相同密钥的项目。

我可以理解 typeof(decimal) 在两个自定义活页夹中导致了这个问题。

您能否指导并帮助我解决此问题。

【问题讨论】:

  • 这看起来像是一个令人难以置信的大黑客。您是否尝试将带逗号的小数转换为带点的小数?
  • @SimonWhitehead 我正在尝试删除逗号。将 4,234,5 转换为 42345。
  • 您可以只添加一个十进制类型的模型绑定器,然后在客户模型绑定器中根据模型名称执行不同的逻辑。

标签: c# .net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

每个数据类型只能有一个模型绑定器。我不完全确定这两个活页夹之间有什么区别,但也许您可以将它们的逻辑组合到一个模型活页夹中。如果您绝对需要两个不同的模型绑定器,那么您可能需要为每个模型绑定器创建两个不同的数据类型。

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2017-08-02
    • 2011-01-27
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多