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,有些直接返回流,有些返回字符串等 ...
随机推荐
- JavaScript 继承方式的实现
1.原型链继承 function superType(name){ this.name= 'milk'; } super.prototype.sayName=function(){ console.l ...
- 网站图片列表动态显示、根据屏幕宽度动态设置DIV的CSS样式
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- WebView缓存
文章从:http://www.360doc.com/content/14/0611/13/15210553_385676271.shtml 摘录而来 当webview加载html页面时,会在/dat ...
- OC 实现多选参数
在iOS的开发过程中有许多方法都是有可选参数的,例如: + (instancetype)arrayWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_N ...
- ACCESS DLL加载错误
如今还在用ACCESS 2003,太懒没办法,升到2010变化太大了,做个Access的转版挺麻烦的.况且大家都在使用2003,也就懒得搞了. 但问题是office 2003已经out了,(Offic ...
- Struts2中ModelDriven的使用
它是Struts2种独有的一种接收用户输入的机制,想在项目中使用模型驱动 (ModelDriven)需要让Action实现com.opensymphony.xwork2.ModelDriven 接口, ...
- 移动端js插件分享
分享几个移动端使用的插件,个人感觉挺不错的. 1. TouchSlide1.1 滑动的焦点图 http://pan.baidu.com/s/1i3J6bbB 2. iscroll.js 模拟滚动条 ...
- Android 数据库ORM框架GreenDao学习心得及使用总结<一>
转: http://www.it165.net/pro/html/201401/9026.html 最近在对开发项目的性能进行优化.由于项目里涉及了大量的缓存处理和数据库运用,需要对数据库进行频繁的读 ...
- php传参方式1--ajax
AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术. AJAX = 异步 JavaScript和 ...
- C 中注意的小问题
输入:char ch[100],gets(ch); scanf("%d",&in); char ch,ch=getchar(); VC: 所有变量声明放在所有操作前面: ...