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);
时间: 2024-10-28 17:14:53

Asp MVC 中处理JSON 日期类型的相关文章

Spring MVC中数据绑定之日期类型

数据绑定应该算是Spring MVC的特点之一吧~简单易用且功能强大,极大地简化了我们编程人员对于用户输入数据的接收及转换. 早先版本的Spring中的数据绑定完全都是基于PropertyEditor的.而Spring3中引入了Converter,用来替代PropertyEditor完成类型转换. 那么我们也依照这个顺序,先来讲讲基于传统的PropertyEditor来实现日期类型的数据绑定. 在Spring MVC中,我们可以通过WebDataBinder来注册自定义的PropertyEdit

Asp.net MVC 中Controller返回值类型ActionResult

内容转自 http://blog.csdn.net/pasic/article/details/7110134 Asp.net MVC中Controller返回值类型 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必须是一个public方法 必须是实例方法 没有标志NonActionAttribute特性的(NoAction) 不能被重载 必须返回ActionResult类型 如: [csharp] view pl

使用Json.Net解决MVC中各种json操作

最近收集了几篇文章,用于替换MVC中各种json操作,微软mvc当然用自家的序列化,速度慢不说,还容易出问题,自定义性也太差,比如得特意解决循环引用的问题,比如datetime的序列化格式,比如性能.NewtonSoft.json也就是Json.Net性能虽然不是最好的,但是是比较靠前的,其功能是最强大的,包含各种json操作模式.现在来看看mvc中的替换1, Controller.Json方法这个方法最容易出现循环引用,比如EF查出一个一对多集合想序列化,结果a引用了子表b,b中还引用了a,导

asp.net中利用JSON进行增删改查中运用到的方法

//asp.net中 利用JSON进行操作, //增加: //当点击"增加链接的时候",弹出增加信息窗口,然后,在窗体中输入完整信息,点击提交按钮. //这里我们需要考虑这些:我会进行异步提交,使用jquery中的方法,$.post("网页名",JSON,callback); //JSON的写法:{"name":name,"id":id},那我们对其进行假设,比方说,表单中的textbox很多,需要我们填写的信息 //也很多,

.net和MVC中的json值和List<T>和DataTable的一些转换

1.List<T>集合转换为Json值 List<ReportModel> dtList = new List<ReportModel>(); JsonResult json = new JsonResult(); json = Json(dtList);//直接采用Json()方法就可以了,不过必须要加载MVC 2.DataTable直接转换为Json值,不过必须加载Newtonsoft.dll这个程序集,大家应该在网上找的到. .net和MVC中的json值和Lis

ASP.NET中使用JSON方便实现前台与后台的数据交换

一.前台向后台请求数据 在页面加载时,有时需要对一些表单进行初始化,此时可以利用JQuery的 get 函数向后台发起异步请求: //初始化函数 function initSettings() { $.get("?Action=init", function (data) { if (data == "NO") { alert("初始化失败!"); } else if (data != null && data != undefi

ASP.NET MVC中常用的ActionResult类型

常见的ActionResult 1.ViewResult 表示一个视图结果,它根据视图模板产生应答内容.对应得Controller方法为View. 2.PartialViewResult 表示一个部分视图结果,与ViewResult本质上一致,只是部分视图不支持母版,对应于ASP.NET,ViewResult相当于一个Page,而PartialViewResult 则相当于一个UserControl.它对应得Controller方法的PartialView. 3.RedirectResult 表

超高性能的json序列化之MVC中使用Json.Net

先不废话,直接上代码 Asp.net MVC自带Json序列化 1 /// <summary> 2 /// 加载组件列表 3 /// </summary> 4 /// <param name="departmentId">作业部/厂</param> 5 /// <param name="unitId">组件Id</param> 6 /// <param name="tag&quo

在ASP MVC中如何使用Angular5导出excel文件

话不多说,直接来实际的. import { Injectable } from '@angular/core';import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';import { Observable } from 'rxjs';@Injectable() 首先引用基础组件. url: string; constructor(private http: HttpClient) { } 声明api路