Does ko.toJSON() work with dates?

后端 未结 2 816
离开以前
离开以前 2021-01-05 07:23

I am using knockoutjs on an asp.net mvc page. I am using ajax to persist a form back to the server by calling ko.toJSON(viewModel) and then posting the results

相关标签:
2条回答
  • 2021-01-05 08:04

    I had a problem with ko.toJSON() giving me a bad date format when the date was DateTime.MinValue.

    Though probably not a fix for your problem, this fix worked for my ko.toJSON() date problem:

    var postData = JSON.parse(JSON.stringify(ko.toJSON(viewModel)).replace(/\"1-01-01/g, "\"0001-01-01"));
    

    ASP.Net WebMethod fails because ko.toJSON() produces different results for DateTime.MinValue

    0 讨论(0)
  • 2021-01-05 08:22

    Given the current issue with ko.toJS and dates, one option would be to create a dependentObservable containing the real value that you want the server to deal with.

    Something like:

    var viewModel = {
        startTimeForInput: ko.observable(),
        type: ko.observable(),
        durationInMinutes: ko.observable(),
        notes: ko.observable()
    };
    
    viewModel.startTime = ko.dependentObservable(function() {
        return this.startTimeForInput().toJSON();
    }, viewModel);
    
    ko.applyBindings(viewModel);
    

    Now, when you call ko.toJSON you will get the startTime with the correct value that the server could use.

    For older browsers, something like json2.js would include the .toJSON for Date objects.

    0 讨论(0)
提交回复
热议问题