我刚刚开始使用
knockout,我遇到了使用JavaScriptSerializer的DateTime序列化和反序列化的麻烦.
我已经从他的博客更新了Steves koListEditor的礼品模型,包括一个修改的DateTime字段:
public class GiftModel { public string Title { get; set; } public double Price { get; set; } public DateTime Modified { get; set; } }
然后我更新了Index.aspx以包含新的字段:
<asp:Content ContentPlaceHolderID="MainContent" runat="server"> <h1>Gift list editor</h1> <p>You have asked for <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>
但是当JavaScriptSerializer序列化模型时
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
修改日期如下:
当使用英国日期I.e 25/01/2011 JavaScriptSerializer.Deserialize抛出以下异常:
25/01/2011 is not a valid value for
DateTime.
虽然我有两个问题在这里主要的问题是有人成功地从MVC 2使用knockout,并得到JavaScriptSerializer与DateTimes工作?我知道我可以编写自己的JavaScriptSerializer,但我希望有一个现成的解决方案在那里:)
以下是Steve Sanderson的koListEditor更新版本的代码:
谢谢
戴夫
@H_502_33@