【问题标题】:How can I remove magic strings from custom model binders?如何从自定义模型绑定器中删除魔术字符串?
【发布时间】:2010-10-04 10:00:25
【问题描述】:

我现在已经编写了几个自定义模型绑定器,并且意识到我已经陷入了依赖魔术字符串的陷阱,例如:

    if (bindingContext.ValueProvider.ContainsPrefix("PaymentKey"))
    {
        paymentKey = bindingContext.ValueProvider.GetValue("PaymentKey").AttemptedValue;
    }

我希望能够使用表达式来强输入前缀名称,但不知道怎么做,希望能得到一些帮助。

谢谢。

【问题讨论】:

  • 您可以创建一个静态类来将这些字符串值保存为属性并改为引用这些属性。例如:bindingContext.ValueProvider.ContainsPrefix(SomeClass.PaymentKey)

标签: asp.net-mvc model-binding magic-string


【解决方案1】:

您要查找的是bindingContext.ModelName,因此您的代码可能变为:

 if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
    {
        paymentKey = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
    }

【讨论】:

  • 感谢您的回答,但不,这不是我要找的。也许我的问题本来可以更清楚,但我正在寻找一种方法来避免对每个属性使用魔术字符串,而不是整个模型。还是谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2019-11-14
相关资源
最近更新 更多