Handling dates with Asp.Net MVC and KnockoutJS

I would suggest a middle man approach through ko.mapping.fromJS( data, mapping ) this would allow you to customize even with a user defined object.

var $data = { _ID : '1', _Created : someDate };  
var $mapping = {
    '_Created' : {
       update: function (options) {
           return convertdata( options.data );
       }
    }
}
var viewDataModel = ko.mapping( data, mapping );  
ko.applyBindings( viewDataModel );

mapping parameter allows you handle changes easily and can easily be leveraged with arrays also.


Personally I think the JSON.NET solution is the best simply because it imposes less on the client. All the other solutions require additional client parsing or additional client code.

I have switched over to using JSON.NET for all of my ASP .NET code that uses JSON because its a much more customizable library.

For example I have had to implement JSON data in MVC that conformed to Google's Chart API (used in combination with Knockout for paging, etc.) and the default JavascriptSerializer simply cannot do it.

In addition with JSON.NET you can customize it to actually spit out full Knockout view models so you don't even need to employ the mapping plugin.

I wrote a sample library called FluentJson.NET which lets you do things in Razor like:

var viewModel = @JsonObject.Create()
    .AddProperty("name", "value")
    .AddObservable("knockoutProperty", 123)

And get:

var viewModel = {"name":"value","knockoutProperty":ko.observable(123)}

So you can get a Knockout view model without any client side hoops to jump through.

You could easily extend something like that to handle date values however you would prefer.