Search code examples
asp.net-mvcmodel-bindingcustom-model-binder

How can I determine the default value of an optional parameter in a custom model binder?


I've got an action method like this:

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

and a custom model binder that handles integer values, so that I can invoke this like so:

/controller/Index?MyBoolean=1

My model binder, in the BindModel method, does this:

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

and this works fine. However, I don't know how to handle the case when the parameter is Optional. I can check that the parameter isn't set, but then I want to return whatever the default value is, and I can't see how to determine that in my model binder. In other words, how can I see that the default value is True, and return that if no value is specified for the MyBoolean property?


Solution

  • It turns out that if you just return False in BindModel, the default MVC model binding will fill the parameter with its default value. Duh.