我刚刚开始使用knockout,并且我在使用JavaScriptSerializer进行DateTime序列化和反序列化时遇到了麻烦。使用默认JavaScriptSerializer绑定DateTime以敲除视图模型
我从他的博客更新史蒂夫koListEditor例如礼品模型包括修改日期时间字段:
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) %>;
修改日期是走出这样的:同样
使用英国日期时,即25/01/2011 JavaScriptSerializer.Deserialize引发以下异常:
25/01/2011不是 DateTime的有效值。
虽然我有2个问题在这里的主要问题是有没有人成功地使用从knockout MVC 2,并得到了JavaScriptSerializer与DateTime是否正常工作?我知道我可以写我自己的JavaScriptSerializer,但我一直希望有一个现成的解决方案在那里:)
下面是史蒂夫·桑德森的koListEditor的更新版本的代码:
感谢
戴夫
任何看着上述..你可以使用JSON.net发送日期到客户端以你想要的任何格式..见http://james.newtonking.com/archive/2009/02/20/good -date-times-with-json-net.aspx – CraftyFella 2011-02-23 19:53:07