如何从自定义模型绑定器中删除魔术字符串?

时间:2021-02-08 19:39:25

I've written a couple of custom model binders now, and have realised that I've fallen into the trap of relying on magic strings, e.g.:

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

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

I'd like to be able to use an expression to strongly-type the prefix names, but can't figure out how, and would be grateful for some assistance.

我希望能够使用表达式强类型化前缀名称,但无法弄清楚如何,并将感谢一些帮助。

Thanks.

1 个解决方案

#1


1  

What you are looking for is bindingContext.ModelName so your code could become:

您正在寻找的是bindingContext.ModelName,因此您的代码可能变为:

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

#1


1  

What you are looking for is bindingContext.ModelName so your code could become:

您正在寻找的是bindingContext.ModelName,因此您的代码可能变为:

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