Asp MVC 中处理JSON 日期类型

时间:2023-03-08 16:20:34
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.

Asp MVC 中处理JSON 日期类型
Add Controller

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

Asp MVC 中处理JSON 日期类型
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:

Asp MVC 中处理JSON 日期类型
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:

Asp MVC 中处理JSON 日期类型
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);