Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer.
I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modified DateTime:
public class GiftModel
{
public string Title { get; set; }
public double Price { get; set; }
public DateTime Modified { get; set; }
}
After updating the Index.aspx to include the new field:
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h1>Gift list editor</h1>
<p>You have requested <span data-bind="text: gifts().length"> </span> gift(s)</p>
<form class="giftListEditor">
<table>
<tbody data-bind="template: { name: 'giftRowTemplate', foreach: gifts }"></tbody>
</table>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
</form>
<script type="text/html" id="giftRowTemplate">
<tr>
<td>Gift name: <input class="required" data-bind="value: Title, uniqueName: true"/></td>
<td>Price: \$ <input class="required number" data-bind="value: Price, uniqueName: true"/></td>
<td>Modified: <input class="required date" data-bind="value: Modified, uniqueName: true"/></td>
<td><a href="#" data-bind="click: function() { viewModel.removeGift($data) }">Delete</a></td>
</tr>
</script>
<script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
var viewModel = {
gifts : ko.observableArray(initialData),
addGift: function () {
this.gifts.push({ Title: "", Price: "", Modified:"" });
},
removeGift: function (gift) {
this.gifts.remove(gift);
},
save: function() {
ko.utils.postJson(location.href, { gifts: this.gifts });
}
};
ko.applyBindings(document.body, viewModel);
$("form").validate({ submitHandler: function() { viewModel.save() } });
</script> </asp:Content>
However, while serializing the Model with JavaScriptSerializer:
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
The Modified Date is not being formatted correctly.
Another issue arises when using UK dates like 25/01/2011, which causes an exception in JavaScriptSerializer.Deserialize:
25/01/2011 is not a valid value for DateTime.
Despite facing these problems, my main concern is if anyone has successfully used knockout with MVC 2 and managed to get the JavaScriptSerializer working properly with DateTimes. I am open to suggestions or existing solutions to tackle this issue.
You can find the updated version of Steve Sanderson's koListEditor code here:
Code on my skydrive
Thank you,
Dave