我剛剛開始使用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