【问题标题】:How can I determine the default value of an optional parameter in a custom model binder?如何确定自定义模型绑定器中可选参数的默认值?
【发布时间】:2015-01-21 14:55:10
【问题描述】:

我有一个这样的动作方法:

Function Index(Optional MyBoolean As Boolean = True) As ActionResult

还有一个处理整数值的自定义模型绑定器,这样我就可以像这样调用它:

/controller/Index?MyBoolean=1

我的模型绑定器,在 BindModel 方法中,这样做:

'convert the string to a boolean
return bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue.ToBoolean, False)

这很好用。 但是,当参数为Optional时,我不知道如何处理。我可以检查该参数是否未设置,但是我想返回默认值,但我看不到如何在我的模型活页夹中确定它。换句话说,我如何才能看到默认值为True,如果MyBoolean 属性没有指定值,则返回?

【问题讨论】:

    标签: asp.net-mvc model-binding custom-model-binder


    【解决方案1】:

    要具有可选参数,变量必须可以为空,这样如果没有传递任何内容,则值将是null。不过,我不确定您为什么要为此创建自定义模型绑定器;默认模型绑定器可以轻松地将字符串转换为布尔值。

    【讨论】:

      【解决方案2】:

      事实证明,如果你只是在BindModel中返回False,默认的MVC模型绑定就会用它的默认值填充参数。呵呵。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-22
        • 2023-03-30
        • 2022-12-16
        • 2012-04-24
        • 2018-10-13
        • 1970-01-01
        • 2015-11-10
        • 2022-01-01
        相关资源
        最近更新 更多