This is a migrated thread and some comments may be shown as answers.
MVVM toJSON() and object properties
2 Answers 138 Views
This is a migrated thread and some comments may be shown as answers.
Russell de Grove
Top achievements
Rank 1
Russell de Grove asked on 29 Jun 2012, 03:16 PM
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 Answers, 1 is accepted

Sort by
0
Roland
Top achievements
Rank 1
answered on 13 Jul 2012, 08:41 AM
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?
0
Roland
Top achievements
Rank 1
answered on 16 Jul 2012, 10:59 AM
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...


Tags
MVVM
Asked by
Russell de Grove
Top achievements
Rank 1
Answers by
Roland
Top achievements
Rank 1
Share this question
or