In my view model I have a IsMale value that has the value true or false.
In my UI I wish to bind it to the following radio buttons:
<label>Male
<input type="radio" name="IsMale" value="true" data-bind="checked:IsMale"/>
</label>
<label>Female
<input type="radio" name="IsMale" value="false" data-bind="checked:IsMale"/>
</label>
The problem I think is checked
expects a string "true" / "false". So my question is, how can I get this 2-way binding w/ this UI and model?
You can also use an extender so it's easy to reuse them for more observables:
Then use it like this:
The parameter provided to
boolForEditing
indicates whether the value may be null.See http://jsfiddle.net/G8qs9/1/
I know this is an old thread, but I was having the same problem and found out a much better solution that was probably added to knockout after this question was officially answered, so I'll just leave it for people with the same problem.
Currently there is no need for extenders, custom binding handlers or computeds. Just provide a "checkedValue" option, it will use that instead of the html 'value' attribute, and with that you can pass any javascript value.
Or:
One option is to use a writeable computed observable.
In this case, I think that a nice option is to make the writeable computed observable a "sub-observable" of your
IsMale
observable. Your view model would look like:You would bind it in your UI like:
Sample: http://jsfiddle.net/rniemeyer/Pjdse/
Once you figure out that the initial match for the radio button wants to match only a string and wants to set the value to a string, it is simply a matter of converting your initial value to string. I had to fight this with Int values.
After you have setup your observables, convert the value to string and KO will do its magic from there. If you are mapping with individual lines, do the conversion in those lines.
In the example code, I'm using Json to map the whole Model in a single command. Then letting Razor insert the value between the quotes for the conversion.
I use a "Dump it all to the screen" at the bottom of my web page during development.
Here are the data values, Before
and, After
In my project, I didn't need to convert Bools, because I'm able to use a checkbox that doesn't have the same frustration.
Use this binder instead of creating stupid ko computed observables.
Example:
Why not simply true and false instead of 1 and 0?