This is the datepicker binding i'm using (im sorry but i forgot where i took it so i can't give the author proper credit. I will edit if i remember.)
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function(event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function(element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
if (widget.date) {
widget.setValue();
}
}
}
};
function Model() {
this.date = ko.observable();
}
function VM() {
this.model = new Model();
this.save = function(model) {
$.post(someEndpoint, {model: model});
}
}
<input type='text' data-bind='datepicker: model().date,
datepickerOptions: { format:"dd/mm/yyyy"}' />
This datepicker binding, and Bootstrap datepicker in general, deals with Date objects. So my observable will contain Dates.
When i post data i see in console that it's posted with natural JS toString() format, which can vary according to your locale settings. For me, its
Mon Dec 02 2013 01:00:00 GMT+0100 (ora solare Europa occidentale)
When i receive this value server-side, i can't handle it because of this weird format.
I could of course rewrite my model date attribute before posting, like so
this.save = function(model) {
model.date(model.date().format('YYYY-MM-DD'));
$.post(someEndpoint, {model: model});
}
but this is not a general purpose solution, furthermore when model.date is updated to string representation, datepicker triggers an error since it's expecting Date.
How would you deal with this?
For Bootstrap 3.0 and higher, these work for me:
Date Only For displaying the date, I use this bindingHandler:
HTML
You'll need Moment.js. The datepicker used for this is located here I'm using a C# backend, and posting to an MVC Controller or Web API controller poses no issues with
DateTime
variables. I.e:Date and Time For displaying, I use this bindingHandler:
For setting the datetime, I use this handler:
HTML
My server side method looks something like this:
With a model similar to this:
The string version of the date (
sFrom
), is generated in my Javascript before I post to the server:Again, this uses Moment.js and this version of the datetimepicker is here