Bind to float / numbers. ("") is added to json model.

200 views
Skip to first unread message

Kenneth

unread,
Mar 5, 2011, 4:10:37 AM3/5/11
to KnockoutJS
Hi

My serialized model is (NewtonSoft):

[{Amount":1.11,"Date":"18-02-2011","Units":29.11}]

I bind to to template:

<script type="text/html" id="expenseRowTemplate">
<tr>
<td><input type="text" data-bind="value: Units, uniqueName:
true" class="number" /></td>
<td><input type="text" data-bind="value: Amount, uniqueName:
true" class="number" /></td>
</tr>
</script>

with:

<tbody data-bind="template: { name: 'expenseRowTemplate', foreach:
expenses }">
</tbody>

Problem is when I change for example the Units value, and console.logs
the model, it becomes:

[{Amount":1.11,"Date":"18-02-2011","Units":"29.11"}]

Note the " around the results. And when I post that to server, it
fails, because it's now a string instead of float.

Any Suggestions?

Ken

rpn

unread,
Mar 5, 2011, 9:38:47 AM3/5/11
to knock...@googlegroups.com
I don't know and didn't look into the exact reason why the number becomes a string, but there is a way to workaround this issue:

You can use a writable dependentObservable to bind to the field.  You provide read and write methods to a writable dependentObservable where you can make sure that your units are written to as a number when someone edits the input field.  Would look like this:

viewModel.unitsForEditing ko.dependentObservable({
    readfunction({
      return viewModel.units();  
    },
    writefunction(value{
         viewModel.units(parseFloat(value));   
    }
});


Hope this helps.  

Peter S

unread,
Mar 7, 2011, 4:51:03 AM3/7/11
to KnockoutJS
How are you deserializing the data? I'm using floats / ints in my
model and ASP.NET happily copes with the quotes when it deserializes
the data back into native .net objects. Can't speak for other methods
though.

Kenneth

unread,
Mar 7, 2011, 5:16:56 AM3/7/11
to KnockoutJS
I'm using the NewtonSoft Json deserializer, which is throwing the
exception.

Ken

rpn

unread,
Mar 9, 2011, 12:19:39 AM3/9/11
to knock...@googlegroups.com
I had another idea about how to handle this one (at least until there would be a more official option to the value binding or to an observable itself).  Basically, the idea would be that you could create a "numericObservable" that would force your input to be numeric.  This would save you from having to have an observable and a corresponding dependentObservable that had to be used in binding.


I described my ideas for ways to use something like this here: http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html

Hope this helps.
Reply all
Reply to author
Forward
0 new messages