MVVM toJSON() and object properties

3 posts, 0 answers
  1. Russell de Grove
    Russell de Grove avatar
    3 posts
    Member since:
    Apr 2010

    Posted 29 Jun 2012 Link to this post

    I'm using MVVM and an Observable (called _alertModel) for a jQuery AJAX post.

    $.ajax({
        url: 'REST/Alert',
        type: 'POST',
        data: _alertModel.toJSON(),
        timeout: 5000,
        dataType: 'json',

    Passing the Observable without calling toJSON does not work.

    If I use toJSON, primitives work fine but objects (Date and Array objects in particular) raise exceptions.

    I've been working around these issues by copying object properties to temporary vars, replacing them with string representations for the AJAX call, restoring the objects after the call is initialized, i.e.

    var date = _alertModel.IncidentDate;  
    _alertModel.IncidentDate = (date.getMonth() + 1) + "/" + date.getDate() + '/' + date.getFullYear();  
        
    $.ajax(...);  
        
    _alertModel.IncidentDate = date;

    This seems clumsy and I'm wondering if there is a better way.
  2. Roland
    Roland avatar
    17 posts
    Member since:
    Aug 2012

    Posted 13 Jul 2012 Link to this post

    I have exact the same problem with parsing my viewmodel with dates to JSON, do you found a better solution than replace the dates to string representation?
  3. Roland
    Roland avatar
    17 posts
    Member since:
    Aug 2012

    Posted 16 Jul 2012 Link to this post

    I'm now using the parseJSON solution from http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html with a ajax converter

    converters: {
                  "text json"function (data) {
                    return $.parseJSON(data, true);
                  }
                }

    before i send the json

    hope this helps you too...


Back to Top