1

I have a knockout viewmodel with dates. Viewmodel Contains a CustomerOrder that contains several BookingRows (orderRows). Each of these viewmodel have dates. I removed a lot of data for readability:

 function ViewModel(data) {
    var self = this;
    self.CustomerOrder = ko.observable(data.CustomerOrder);
    self.AllTreatments = data.AllTreatments;
    self.AllTreatmentGroups = data.AllTreatmentGroups;
    self.AllTreatmentRooms = data.AllTreatmentRooms;
    ...
    self.Save {
       var dataToSave = ko.toJSON({ CustomerOrder: self.CustomerOrder });
       AjaxSaveCustomerOrder(dataToSave);
    }
}

var CustomerOrder = function (data) {
    var self = this;

    ....

    self.CustomerOrderDate = ko.observable(data.CustomerOrderDate);
    self.Bookings = ko.observableArray($.map(data.Bookings, function(item) {
         return new Booking(item);
       }) || []);
}; 

When I look at the post, the dates are sent as JSon Dates like this:

CustomerOrderDate":"/Date(1361981980121)/

It is not parsed as a date to my viewmodel where it is a DateTime.

Any sugestions how to do this is appreciated.

ekenman
  • 995
  • 1
  • 13
  • 29
  • 1
    JSON does not do dates. Probably easiest to pass them back as strings and parse them using client side javascript. (http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx) – paul Feb 27 '13 at 16:48

2 Answers2

0

You should parse date value and create Date object manually.

self.CustomOrderDate = ko.observable(new Date(+data.CustomerOrderDate.replace(/\/Date\((\d+)\)\//, '$1')));
Rango
  • 3,877
  • 2
  • 22
  • 32
  • It's the POST, when serialising back to my MVC-object that is not working. From MVC model -> KO works just fine. – ekenman Feb 28 '13 at 08:05
0

Thank you Paul for pointing me in the right direction.

I now use Newton JSON to serialize TO the KO viewmodel like this:

 var viewModel = ko.mapping.fromJS(@(Html.Raw(JsonConvert.SerializeObject(Model, new IsoDateTimeConverter()))));    

Then the dates passed back to the server are ISO and "Microsoft dates". It seems KO handles both formats and just passes back what it gets.

This post also gives some more information: Handling dates with Asp.Net MVC and KnockoutJS

Community
  • 1
  • 1
ekenman
  • 995
  • 1
  • 13
  • 29