我最近开始使用KnockoutJs,并很快意识到使用默认的Json(myModelWithADate)会产生默认的json编码\/Date(-62135578800000)\/.通过一些研究,我找到了四种可能的方法来处理dom元素中日期的显示.

1) Create a binding that handles the conversion from the Json date to the format you desire

ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var jsonDate = valueAccessor();
        var value = new Date(parseInt(jsonDate.substr(6)));
        var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
        element.innerHTML = ret;
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    }
};

用法

<td data-bind="date: DueDate">
</td>

2) Return “strings” from your Controller

return Json(new {MyDate = DateTime.Now.ToShortDateString()});

3) Use the JSON.NET to specify a Date Time format seen over at 100

示例

string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

4) use JSON.parse to handle your dates as seen in this 100

JSON.parse(jsonText, function(key, value) {
    // Check for the /Date(x)/ pattern
    var match = /\/Date\((\d+)\)\//.exec(value);
    if (match) {
        var date = new Date(+match[1]); // Convert the ticks to a Date object
        return humanReadable(date); // Format the date how you want it
    }

    // Not a date, so return the original value
    return value;
});

它们似乎都很管用,但我仍在为哪一种感觉"正确"而苦苦挣扎.现在,我的直觉是混合使用绑定和返回字符串.正如我可以看到的那样,我自己扩展了绑定以使用jQuery UI Datepicker控件处理输入.

Is there an accepted practice when handling displaying dates or other types such as currency? Is there another option I am missing that solves this problem?

推荐答案

就我个人而言,我认为JSON.NET解决方案是最好的,因为它对客户施加的压力更小.所有其他解决方案都需要额外的客户端解析或额外的客户端代码.

我已经转而使用JSON.NET为我所有的ASP.NET代码使用JSON,因为它是一个可定制得多的库.

例如,我必须在MVC中实现符合Google's Chart API的JSON数据(与用于分页的Knockout结合使用,等等),而默认的JavascriptSerializer根本无法做到这一点.

此外还有JSON.NET,你可以定制它,让它真正地展现出完整的淘汰视图模型,所以你甚至不需要使用映射插件.

我编写了一个名为FluentJson.NET的示例库,它可以让你像剃刀一样做事情:

var viewModel = @JsonObject.Create()
    .AddProperty("name", "value")
    .AddObservable("knockoutProperty", 123)

然后得到:

var viewModel = {"name":"value","knockoutProperty":ko.observable(123)}

因此,您可以获得一个淘汰视图模型,而无需任何客户端环.

你可以很容易地扩展类似的东西来处理日期值.

Asp.net相关问答推荐

httpCompression 和 urlCompression 有什么区别?

IIS Request.UserHostAddress 返回 IPV6 (::1),即使禁用了 IPV6

更改 GridView 中列的标题文本

为什么默认情况下不允许 GET 请求返回 JSON?

如何在asp.net中判断会话是否过期

如何在 ASP.NET 应用程序中使用 jQuery 捕获提交事件?

为什么 Asp.Net Identity IdentityDbContext 是一个黑盒?

获取页面上特定类型的所有 Web 控件

在 ApiController 中添加自定义响应头

带有 2 个提交按钮/操作的 ASP.Net MVC 4 表单

这个rendersection的代码是什么意思?

使用 Ninject OWIN 中间件在 OWIN 启动中注入 UserStore

如何获取当前登录用户的角色列表

如何保护存储在 web.config 中的密码?

在 ASP.NET 中使用 MasterPages 时使用 JQuery 的正确方法?

使用 .NET 连接到 AS400

HttpContext.Current属性的跨线程使用及相关的东西

如何告诉 RadioButtonList 不生成表格

ExecuteReader:连接属性尚未初始化

中继器中的中继器