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,有些直接返回流,有些返回字符串等 ...
随机推荐
- html系列教程--link mark meta
<link> 标签:定义文档与外部资源的关系,常见的用途是链接样式表 demo: <link rel="stylesheet" type="text/c ...
- C# foreach获取集合元素索引的坑
,}; foreach(var prepareId in prepareIds) { Console.WriteLine(prepareIds.IndexOf(prepareId)); } 执行结果如 ...
- Java Class类以及获取Class实例的三种方式
T - 由此 Class 对象建模的类的类型.例如,String.class 的类型是Class<String>.如果将被建模的类未知,则使用Class<?>. publi ...
- c++中类模版中的static数据成员的定义
这个有点绕. 如下: template <typename T> class A{ ......... static std::allocate<T> alloc_; }; t ...
- lightoj 1064 Throwing Dice
题意:给你n个骰子,求n个骰子的和不小于x的概率. 刚开始想每给一组数就计算一次~~太笨了- -,看了别人的代码,用dp,而且是一次就初始化完成,每次取对应的数据就行了.WA了好多次啊,首先不明白的就 ...
- [转]前端CSS规范整理
一.文件规范 1.文件均归档至约定的目录中. 具体要求通过豆瓣的CSS规范进行讲解: 所有的CSS分为两大类:通用类和业务类.通用的CSS文件,放在如下目录中: 基本样式库 /css/core 通用 ...
- EBS 开发中如何动态启用和禁止请求(Current Request)的参数
EBS 开发中如何动态启用和禁止请求(Current Request)的参数 (版权声明,本人原创或者翻译的文章如需转载,如转载用于个人学习,请注明出处:否则请与本人联系,违者必究) 我们可以使用依赖 ...
- 移动跨平台开发框架Ionic开发一个新闻阅读APP
移动跨平台开发框架Ionic开发一个新闻阅读APP 前言 这是一个系列文章,从环境搭建开始讲解,包括网络数据请求,将持续更新到项目完结.实战开发中遇到的各种问题的解决方案,也都将毫无保留的分享给大家. ...
- 致命错误C0000034正在应用更新操作37解决方法
当碰到这个问题的时候关闭电脑,启动,不断按F8键,进入命令行,输入Notepad.exe弹出记事本,文件,打开,所有文件,然后将C:\Windows\WinSxS目录下的pending.xml文件中的 ...
- php面向对象编程学习之高级特性
前几天写了一篇关于php面向对象基础知识的博客,这两天看了php面向对象的高级特性,写出来记录一下吧,方便以后拿出来复习. 面向对象除了最基本的定义类之外,最主要就是因为面向的一些高级特性,运用这些高 ...