I recently started working with KnockoutJs and quickly realized using the default Json(myModelWithADate) resulted in the default json encoding of \\/Date(
I always use a data converter instead of sending data directly to server to fix any client encoding or parsing issues, without the need to use additional tools.
In the Knockout JS view model file, I add the following code before the view model setup, which intercept selected proeprries of the view model and use moment.js to take care of date convertions:
// converting data before sending to controller
var dataConverter = function (key, value) {
if (key === 'InvoiceDate') {
return moment(value).format("YYYY MMMM DD");
}
return value;
};
Then I use the dataConverter instead of data in the ajax save method within the view model:
// Example view model for sales invoice
SalesInvoiceViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.SaveInvoice = function () {
$.ajax({
url: '/SalesInvoices/SaveInvoice/',
type: 'POST',
data: ko.toJSON(self, **dataConverter**),
contentType: 'application/json',
success: function (data) {
if (data.invoiceViewModel !== null) {
ko.mapping.fromJS(data.invoiceViewModel, {}, self);
}
if (data.redirectToLocation !== null) {
window.location = data.redirectToLocation;
}
},
error: function (xhr, ajaxOptions, thrownError) {
// report error to user
}
});
}