0

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?

Joshua Frank
  • 13,120
  • 11
  • 46
  • 95

2 Answers2

0

To have an optional parameter, the variable must be nullable, such that if nothing is passed the value will be null. I'm not sure why you created a custom model binder for this, though; the default model binder can easily convert a string to a bool.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

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.

Joshua Frank
  • 13,120
  • 11
  • 46
  • 95