0

I am posting data to a controller stringified by knockout:

var data = ko.toJSON(viewModel);

$.ajax({
    type: 'POST',
    url: '@Url.Action("Action")',
    data: { data: data },
    dataType: 'json'
    ....
})

Then server-side, I try to deserialize the data with JsonConvert.

var viewModel = JsonConvert.DeserializeObject<ViewModel>(data,
        new JsonSerializerSettings
        {
            DateTimeZoneHandling = DateTimeZoneHandling.Local,
            DateFormatHandling = DateFormatHandling.IsoDateFormat
        });

This fails if data contains null values (serialized as "NaN"), looking like this:

"MyField":"NaN"

Without null values, it works fine.

I tried adding NullValueHandling = NullValueHandling.Include/Ignore to the serializer settings, both without success.

Leonardo Henriques
  • 784
  • 1
  • 7
  • 22
AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
  • What does your ViewModel class look like? – UmmmActually May 16 '18 at 15:57
  • 2
    How about not sending `NaN` then? That seems like the sensible solution rather than trying to handle them. – DavidG May 16 '18 at 15:58
  • Hi David, I tried this, somehow didn't work, will try again to make it work – AGuyCalledGerald May 16 '18 at 16:03
  • Why are you serializing null values as NaN instead of null? –  May 16 '18 at 18:28
  • I think we need to see a [mcve] to help you on this one, including a sample `ViewModel` and JSON that reproduce the problem. Also, what version of Json.NET are you using? Their handling of `NaN` for doubles has changed over the years, see e.g. https://github.com/JamesNK/Newtonsoft.Json/releases/tag/9.0.1 and https://github.com/JamesNK/Newtonsoft.Json/releases/tag/5.0.1. – dbc May 16 '18 at 18:31
  • 1
    Also, is this what you need? [Removing NaN values in deserialization Web API 2 C#](https://stackoverflow.com/q/42682371/3744182). – dbc May 16 '18 at 18:34

1 Answers1

1

I got around the problem by adding a small replacer function to the knockout stringifier (as suggested by DavidG - thank you, I should have made this work from the beginning).

var data = ko.toJSON(viewModel, function (key, value) { 
    if (value == "NaN") {
        return;
    }
    else {
        return value;
    }
});
AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120