javascript 使用默认的 JavaScriptSerializer 将 DateTime 绑定到淘汰赛模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4798502/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding DateTime to knockout view model with default JavaScriptSerializer
提问by CraftyFella
I've just started using knockoutand I'm running into trouble with DateTime Serialization and Deserialization using the JavaScriptSerializer.
我刚刚开始使用淘汰赛,但在使用 JavaScriptSerializer 进行 DateTime 序列化和反序列化时遇到了麻烦。
I've updated the gifts model in Steves koListEditorexample from his blog to include a Modified DateTime field:
我已经更新了他博客中 Steves koListEditor示例中的礼物模型,以包含一个修改的日期时间字段:
public class GiftModel
{
    public string Title { get; set; }
    public double Price { get; set; }
    public DateTime Modified { get; set; }
}
Then I updated the Index.aspx to include the new field:
然后我更新了 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>
However when the JavaScriptSerializer serializes the Model
但是当 JavaScriptSerializer 序列化模型时
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
the Modified Date is coming out like this:
修改日期是这样出来的:


Also when using UK Dates I.e. 25/01/2011 the JavaScriptSerializer.Deserialize throws the following exception:
此外,当使用英国日期即 25/01/2011 时,JavaScriptSerializer.Deserialize 会引发以下异常:
25/01/2011 is not a valid value for DateTime.
25/01/2011 不是 DateTime 的有效值。
Although i'm having 2 problems here the main question is has anyone successfully used knockoutfrom MVC 2 and got the JavaScriptSerializer working with DateTimes? I realise I could write my own JavaScriptSerializer but I was hoping there was a ready made solution out there :)
尽管我在这里遇到了 2 个问题,但主要问题是有人成功地使用了 MVC 2 的淘汰赛并让 JavaScriptSerializer 与 DateTimes 一起工作吗?我意识到我可以编写自己的 JavaScriptSerializer,但我希望有一个现成的解决方案:)
Here's the code for the updated version of Steve Sanderson's koListEditor:
这是 Steve Sanderson 的 koListEditor 更新版本的代码:
Thanks
谢谢
Dave
戴夫
回答by Sergei Golos
Well there are two options. You could do the simple fix by having a designated view model object which stores the preformated date time values as a string. This is generally what i do. I can then tryparse for the date value for validation.
那么有两种选择。您可以通过指定的视图模型对象来完成简单的修复,该对象将预先格式化的日期时间值存储为字符串。这通常是我所做的。然后我可以尝试解析日期值以进行验证。
The other option would be to implement a custom data binding. You can look at doing that here. This would be the more elegant approach. The nice thing about this apporach, you can then create you UI generation code on binding allowing you to add date picker to the ui in the process.
另一种选择是实现自定义数据绑定。您可以在此处查看这样做。这将是更优雅的方法。这个方法的好处是,您可以在绑定时创建 UI 生成代码,允许您在此过程中将日期选择器添加到 ui。
回答by Don Smith
Not an elegant solution, but it works:
不是一个优雅的解决方案,但它有效:
data-bind="value: eval('new ' + Modified.slice(1,-1)), uniqueName: true"
data-bind="value: eval('new ' + Modified.slice(1,-1)), uniqueName: true"
Evalmight be a security issue here depending on the context.
Eval根据上下文,这里可能是一个安全问题。

