Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling dates with Asp.Net MVC and KnockoutJS

I recently started working with KnockoutJs and quickly realized using the default Json(myModelWithADate) resulted in the default json encoding of \/Date(-62135578800000)\/ With a bit of research I located four potential ways to handle the display of my dates in dom elements.

1) Create a binding that handles the conversion from the Json date to the format you desire

ko.bindingHandlers.date = {     init: function (element, valueAccessor, allBindingsAccessor, viewModel) {         var jsonDate = valueAccessor();         var value = new Date(parseInt(jsonDate.substr(6)));         var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();         element.innerHTML = ret;     },     update: function(element, valueAccessor, allBindingsAccessor, viewModel) {      } }; 

Usage

<td data-bind="date: DueDate"> </td> 

2) Return “strings” from your Controller

return Json(new {MyDate = DateTime.Now.ToShortDateString()}); 

3) Use the JSON.NET to specify a Date Time format seen over at james.newtonking.com

Example

string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter()); // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"} 

4) use JSON.parse to handle your dates as seen in this stackoverflow answer.

JSON.parse(jsonText, function(key, value) {     // Check for the /Date(x)/ pattern     var match = /\/Date\((\d+)\)\//.exec(value);     if (match) {         var date = new Date(+match[1]); // Convert the ticks to a Date object         return humanReadable(date); // Format the date how you want it     }      // Not a date, so return the original value     return value; }); 

They all appear to work, but I am still struggling with which one feels “right”. Right now my gut is going with a mix with the binding and returning strings. As I could see myself extending the binding to handle input with jQuery UI datepicker controls.

Is there an accepted practice when handling displaying dates or other types such as currency? Is there another option I am missing that solves this problem?

like image 696
Mark Coleman Avatar asked Jan 04 '12 23:01

Mark Coleman


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM patternMVVM patternMVVM is a variation of Martin Fowler's Presentation Model design pattern. It was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces. The pattern was incorporated into the Windows Presentation Foundation (WPF) (Microsoft's .https://en.wikipedia.org › wikiModel–view–viewmodel - Wikipedia that helps developers build rich and responsive websites.

How to add Knockout JS in ASP net MVC?

Create a new project in ASP.NET MVC 4 and name it as you prefer and select empty project template. Install Entity Framework 6, Jquery and Knockout in your project using NuGet Package Manager. You can also download jquery. js and Knockout.

What is Knockout JS in asp net?

Knockout. Js (simply KO) is a powerful JavaScript library which allows developers to bind DOM elements with any data model like array, Json etc.


2 Answers

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.

like image 123
Paul Tyng Avatar answered Sep 24 '22 21:09

Paul Tyng


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.

like image 25
Andres Toro Avatar answered Sep 22 '22 21:09

Andres Toro