I recently started working with KnockoutJs and quickly realized using the default Json(myModelWithADate)
resulted in the default json encoding of \\/Date(
I'm using the following code to generate short date strings. I use it for my date strings and jQueryUi Date Picker.
class T
{
public DateTime d { get; set; }
}
static void Main(string[] args)
{
var k = new T { d = DateTime.Now };
var formatter = new IsoDateTimeConverter();
formatter.DateTimeFormat = "d";
var s = JsonConvert.SerializeObject(k, formatter);
}
This generates the following JSON
"{"d":"4/21/2012"}"
This results clean JavaScript code for me.
I loved Andres Toro's answer except that in my case, input fields are expecting formatted strings. So I am using JQuery to format my dates according to my favorite format provided by my helper @Html.ConvertDateFormat()
Hope this helps someone day.
var mapping = {
'ActualDateTime': {
update: function (options) {
var d = /\/Date\((\d*)\)\//.exec(options.data);
return (d) ? $.datepicker.formatDate('@Html.ConvertDateFormat()', new Date(+d[1])) : value;
//return "5/10/2017";
}
}
};
var paymentModel = ko.mapping.fromJS(modelJSON, mapping);