Example with DateTime

152 views
Skip to first unread message

Alexey Boyko

unread,
Oct 2, 2014, 6:28:19 AM10/2/14
to knocko...@googlegroups.com

Hello

There is a DateTime field in C# MVC model

public class EventViewModel
{
   
public DateTime? EventStart { get; set; }

}

Autorender js-code is
<script type="text/javascript">
   
var viewModelJs = {"EventStart":"2014-10-02T14:21:03.5484971+04:00"};
   
var viewModel = ko.mapping.fromJS(viewModelJs);
   ko
.applyBindings(viewModel);
</script>

"EventStart" field is string, not a date. We need that the knockout model will be similat to this, the "EventStart" filed is type of DateTime
var ViewModel = function() {
   
this.EventStart = ko.observable(new Date()); // here must be real date from C# MVC model
};

How can we achieve this?
Thank you!

KE

unread,
Jan 23, 2015, 6:07:13 PM1/23/15
to knocko...@googlegroups.com
Any solution on this? 

Nigel Whatling

unread,
Jan 23, 2015, 7:05:48 PM1/23/15
to knocko...@googlegroups.com
Knockout MVC uses Json.NET to serialise your model to JSON. Difficulties with dates has been written about on a number of occasions (e.g. http://james.newtonking.com/archive/2009/02/20/good-date-times-with-json-net). Using the JavaScriptDateTimeConverter from Json.NET, you can achieve what you want. Your model would become:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class EventViewModel
{
   
[JsonConverter(typeof(JavaScriptDateTimeConverter))]

   
public DateTime? EventStart { get; set; }
}


Bear in mind that as the article points out, this produces JSON that does not technically follow the specification. My preference would be to convert the data after mapping if you absolutely had to have Date objects.

KE

unread,
Jan 26, 2015, 11:04:52 AM1/26/15
to knocko...@googlegroups.com
If you needed to capture both date and time, and you wanted to utilize knockoutMVC...    would you use 1 datetime model objects or 2  (one for date and one for time), and then on form submission merge them together. 

I'm not getting my head around how to use KnockoutMVC with the datetime viewmodel object  and elegantly allow the user to capture both date and time...  

Nigel Whatling

unread,
Jan 26, 2015, 7:04:03 PM1/26/15
to knocko...@googlegroups.com
It will really depend on what UI elements you use. If you want to use the HTML5 datetime input type, you will have to construct the element manually because KnockoutMVC doesn't directly support it. You will also need to ignore the previous comment about JavaScriptDateTimeConverter. But you could also choose to capture that information in a number of other ways (e.g. series of dropdown boxes) and your model structure would need to match those requirements.
Reply all
Reply to author
Forward
0 new messages