Asp MVC 中处理JSON 日期类型
注:时间有点忙,直接copy 过来的,要查看原址:
http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html
Introduction
Most of the time, data transfer during Ajax communication is facilitated using JSON format. While JSON format is text based, lightweight and simple it doesn't offer many data types. The data types supported in JSON include string, number, boolean, array, object and null. This support for limited data types poses some difficulties while dealing with dates. Since there is no special representation for dates in JSON, ASP.NET uses its own way to deal with dates. This article discusses how dates are serialized in JSON format by MVC action methods and how to deal with them in your client side jQuery code.
Brief Overview of JSON Format
Before we go ahead and discuss the problem we're faced with while dealing with the date data type, let's quickly see what JSON is and how data is represented in JSON format.
JSON stands for JavaScript Object Notation. JSON is a light-weight text based format for data exchange. Using JSON format you can pack the data that needs to be transferred between the client and the server. As mentioned earlier JSON supports strings, numbers, Boolean, arrays, objects and null data types. A frequently used data type missing from JSON is DateTime. An object in JSON format typically consists of one or more name-value pairs. The object begins with { and ends with }. The name-value pairs are placed in between the brackets. A property name and its value are enclosed in double quotes ("..."). A property and its value are separated by a colon (:). Multiple name-value pairs are delimited by a comma(,).
Using JSON format you essentially represent objects. In that respect JSON is quite similar to JavaScript objects. However, it is important to remember that although JavaScript objects and JSON objects look quite similar these two formats are not exactly the same. For example, JavaScript object properties can be enclosed in single quotes ('...'), double quotes ("...") or you can omit using quotes altogether. JSON format on the other hand requires you to enclose property names in double quotes.
The following code shows an object represented in JSON format:
var customer ={
"CustomerID":100,
"CompanyName":"Some Company",
"ContactName":"Some Name",
"IsActive":true;
};
Once created, you can use a JSON object similar to a JavaScript object. For example, the following code retrieves the CompanyName and ContactName properties of the customer object and displays them in an alert dialog.
alert(customer.CompanyName + " - " + customer.ContactName);
Understanding the Problem
Now that you know basics of JSON format, let's look at the problem while dealing with dates. Since JSON doesn't have any special representation for dates; they are serialized as plain strings. This makes it difficult to interpret and convert the date values into JavaScript dates or .NET dates. As a solution the default serialization mechanism of ASP.NET Web Forms and MVC serializes dates in a special form - \/Date(ticks)\/ - where ticks is the number of milliseconds since 1 January 1970.
Note:
ASP.NET Web API uses ISO date format by default while serializing dates.
To understand the issue better, let's create an ASP.NET MVC application that sends Order information including order date and shipping date to the client in JSON format. Begin by creating a new ASP.NET MVC4 application and add HomeController to it.

Add Controller
Also, add an Entity Data Model (.edmx) for Orders table of the Northwind database to the Models folder.

Order
Then add an action method named GetOrder() to the Home controller as shown below.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetOrder()
{
NorthwindEntities db = new NorthwindEntities();
var data = from o in db.Orders
select o;
return Json(data.FirstOrDefault(),JsonRequestBehavior.AllowGet);
}
}
As you can see the HomeController class has the GetOrder() action method. The GetOrder() method selects orders from the Orders table and returns the first order to the caller using the FirstOrDefault() method. Notice how the Order object is returned to the caller. The GetOrder() returns JsonResult. The Json() method accepts any .NET object and returns its JSON representation. The JSON data is then sent to the caller. While converting Order object to JSON format the default serializer of ASP.NET represents dates using the format mentioned at the beginning of this section.
To invoke the GetOrder() action method from the client side, write the following jQuery code in the Index view.
$(document).ready(function () {
$("#Button1").click(function (evt) {
var options = {};
options.url = "/Home/GetOrder";
options.dataType = "json";
options.contentType = "application/json";
options.success = function (order) {
alert("Required Date : " + order.RequiredDate + ", Shipped Date : " + order.ShippedDate);
};
options.error = function () { alert("Error retrieving employee data!"); };
$.ajax(options);
});
});
The above code assumes that you have a button on the Index view whose ID is Button1. The click event handler of Button1 uses $.ajax() to call the GetOrder() action method. The options object stores various settings such as url, type as well as success and error handlers. Notice how the url property points to /Home/GetOrder. The success function receives JSON representation of Order as returned by the GetOrder() action method. The order object can then be used to display RequiredDate and ShippedDate values.
If you invoke the method using jQuery and look at the Order object using Chrome developer tools you will see this:

Order Object Results
As you can see all the dates are represented as \/Date(ticks)\/. These dates cannot be consumed in JavaScript code in their current form. In order to use these date values in JavaScript you first need to convert them to JavaScript Date object.
Client Side Solution
Now that you know the problem with date serialization in ASP.NET MVC, let's see how to overcome it. One, possibly the simplest, way is to grab the date returned from the server side and extract the ticks from it. You can then construct a JavaScript Date object based on these ticks. The following code shows ToJavaScriptDate() function that does this for you:
function ToJavaScriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
The ToJavaScriptDate() function accepts a value in \/Date(ticks)\/ format and returns a date string in MM/dd/yyyy format. Inside, the ToJavaScriptDate() function uses a regular expression that represents a pattern /Date\(([^)]+)\)/. The exec() method accepts the source date value and tests for a match in the value. The return value of exec() is an array. In this case the second element of the results array (results[1]) holds the ticks part of the source date. For example, if the source value is \/Date(836418600000)\/ then results[1] will be 836418600000. Based on this ticks value a JavaScript Date object is formed. The Date object has a constructor that accepts the number of milliseconds since 1 January 1970. Thus dt holds a valid JavaScript Date object. The ToJavaScriptDate() function then formats the date as MM/dd/yyyy and returns to the caller. You can use the ToJavaScriptDate() function as shown below:
options.success = function (order) {
alert("Required Date : " + ToJavaScriptDate(order.RequiredDate) + ", Shipped Date : " + ToJavaScriptDate(order.ShippedDate));
};
Although the above example uses date in MM/dd/yyyy format, you are free to use any other format once a Date object is constructed.
Server Side Solution
The previous solution uses a client side script to convert the date to a JavaScript Date object. You can also use server side code that serializes .NET DateTime instances in the format of your choice. A modern trend is to send dates on the wire using ISO format - yyyy-MM-ddThh:mm:ss. To accomplish this task you need to create your own ActionResult and then serialize the data the way you want. As far as ASP.NET MVC applications are concerned, Json.NET (a popular library to work with JSON in .NET applications) is your best choice for serializing the data. Unlike the default serializer that comes with ASP.NET, Json.NET serializes dates in ISO format.
To demonstrate how the server side technique can be implemented, add a JsonNetResult class in your project that inherits from the JsonResult base class. The following code shows the skeleton of this class:
public class JsonNetResult : JsonResult
{
public object Data { get; set; }
public JsonNetResult()
{
}
...
}
The JsonNetResult class has a public property - Data - that holds the object to be serialized in JSON format. Then override the ExecuteResult() method of the base class as shown below:
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings());
serializer.Serialize(writer, Data);
writer.Flush();
}
}
The above code uses the JsonTextWriter class to write JSON data onto the response stream. The JsonTextWriter class represents a fast, non-cached, forward-only writer that writes JSON data onto the underlying stream. The JsonSerializer class allows you to serialize and deserialize objects in JSON format. The Serialize() method writes the Data object to the JsonTextWriter created earlier. The Data object will be supplied from the action method code.
Once you create the JsonNetResult class, modify the GetOrder() action method like this:
public JsonNetResult GetOrder(DateTime id)
{
NorthwindEntities db = new NorthwindEntities();
var data = from o in db.Orders
where o.OrderDate == id
select o;
return new JsonNetResult() { Data=data.FirstOrDefault() };
}
As you can see the GetOrder() method now returns JsonNetResult instead of JsonResult. Notice how the data is returned. A new instance of JsonNetResult is created and its Data property is set to the Order object obtained from the FirstOrDefault() method.
If you run the client side jQuery code again, this time you will get dates in ISO date format. You can also confirm this using Chrome developer tools:

ISO Date Format
As you can see all the dates are now returned as yyyy-MM-ddThh:mm:ss format. To convert these date values into JavaScript is quite simple. You can simply pass them to Date constructor and parse them into a Date object like this:
var dt = new Date(order.ShippingDate);
Asp MVC 中处理JSON 日期类型的更多相关文章
- Asp.net MVC 中Controller返回值类型ActionResult
[Asp.net MVC中Controller返回值类型] 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必 ...
- MVC中处理Json和JS中处理Json对象
MVC中处理Json和JS中处理Json对象 ASP.NET MVC 很好的封装了Json,本文介绍MVC中处理Json和JS中处理Json对象,并提供详细的示例代码供参考. MVC中已经很好的封装了 ...
- net.sf.json日期类型格式化输出
net.sf.json 日期类型格式化输出 Date, Timestamp ; 编写工具类 package cn.jorcen.commons.util; import java.text.DateF ...
- 使用Json.Net解决MVC中各种json操作
最近收集了几篇文章,用于替换MVC中各种json操作,微软mvc当然用自家的序列化,速度慢不说,还容易出问题,自定义性也太差,比如得特意解决循环引用的问题,比如datetime的序列化格式,比如性能. ...
- ASP.NET中使用JSON方便实现前台与后台的数据交换
ASP.NET中使用JSON方便实现前台与后台的数据交换 发表于2014/9/13 6:47:08 8652人阅读 分类: ASP.NET Jquery extjs 一.前台向后台请求数据 在页面加 ...
- asp.net中的时间日期选择控件
asp.net中的时间日期选择控件 Posted on 2008-07-17 17:37 飛雪飄寒 阅读(22922) 评论(6) 编辑 收藏 在系统中经常需要进行时间日期选择(比如查询时间范 ...
- asp.net中利用JSON进行增删改查中运用到的方法
//asp.net中 利用JSON进行操作, //增加: //当点击“增加链接的时候”,弹出增加信息窗口,然后,在窗体中输入完整信息,点击提交按钮. //这里我们需要考虑这些:我会进行异步提交,使用j ...
- ASP.NET MVC中常用的ActionResult类型
常见的ActionResult 1.ViewResult 表示一个视图结果,它根据视图模板产生应答内容.对应得Controller方法为View. 2.PartialViewResult 表示一个部分 ...
- .Net Mvc学习——ASP.NET MVC中常用的ActionResult类型
一.定义 MVC中ActionResult是Action的返回结果.ActionResult 有多个派生类,每个子类功能均不同,并不是所有的子类都需要返回视图View,有些直接返回流,有些返回字符串等 ...
随机推荐
- tomcat学习(-)windows 7 x64 配置tomcat服务
下载Tomcat 下载地址:http://tomcat.apache.org/ 安装版本:Tomcat 9.0 安装环境:windows 7 x64 阅读Tomcat文档 文档路径:http://lo ...
- NHibernate 3.3
今天试了一下NHibernate 3.3比之前的版本简单,只需要引入两个dll,这两个dll分别是:Iesi.Collections.dll和NHibernate.dll 通过 http://nhfo ...
- iOS技术
iOS技术 OC:分类(好处,和延展的区别) 分类: 在不修改原有的类的基础上增加新的方法 一个庞大的类可以分模块开发 一个庞大的类可以由多个人来编写,更有利于团队合作 分类是对原有类的一种扩展,在 ...
- spring与hibernate整合事务管理的理解
在谈Spring事务管理之前我们想一下在我们不用Spring的时候,在Hibernate中我们是怎么进行数据操作的.在Hibernate中我们每次进行一个操作的的时候我们都是要先开启事务,然后进行数据 ...
- centos5.5用phpstudy一键安装配置虚拟主机后,yum配置代理服务器squid
最近因为工作需要,开发站点需要在lamp环境下跑网站,于是在win7上跑虚拟机装了一个centos5.5的linux 并用集成环境配置了一个lamp环境,这里用的是phpstudy的一键安装包,并配置 ...
- Flot chart学习笔记
背景及相关简介 在最近的BS新项目中需要用到绘图数据显示的功能.在进行充足的选择之后决定才去开源的Flot.Flot是一个jQuery绘图库.主要用于简单的绘制图表功能.具有吸引人的渲染外观和互操作的 ...
- poj 2723 Get Luffy Out 二分+2-sat
题目链接 给n个钥匙对, 每个钥匙对里有两个钥匙, 并且只能选择一个. 有m扇门, 每个门上有两个锁, 只要打开其中一个就可以通往下一扇门. 问你最多可以打开多少个门. 对于每个钥匙对, 如果选择了其 ...
- codeforces 8D Two Friends 二分+ 判断三个圆是否有公共交点
题目链接 有两个人x, y, 现在在A点, x要直接去B点, y要先去C点在去B点, 现在给出x, y两人可以行走的最大距离T1, T2, 求出他们从A点出发之后, 可以走的最长的公共路径. 我们先看 ...
- CSS自学笔记(6):CSS的模型
CSS 框模型 (Box Model) 规定了元素框处理元素内容.内边距.边框和外边距的方式. 图片来源:w3school.com.cn 元素(element)是一个html文档的实际内容区域,依次由 ...
- IE WebDriver 因保护模式无法启动的解决 (转载)
现在Win7 已经应用很多了,即使是最原始的Win7 也是IE8,最新的patch后,都升到了IE11 Win7下预装高版本IE的情况下,启动IE WebDriver可能会出现: org.openqa ...