Working with JSON date types in ASP MVC

Source: Internet
Author: User
Tags chrome developer chrome developer tools

Note: Time is a bit busy, direct copy came, to see the original: 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 was 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 limited data types poses some difficulties and dealing with dates. Since There is no special representation for dates in JSON, ASP. NET uses its own a-to-deal with dates. This article discusses how dates is serialized in JSON format by MVC action methods and what to deal with them in your CLI ENT side jQuery code.

Brief Overview of JSON Format

Before we go ahead and discuss the problem we ' re faced with when dealing with the date data type, let's quickly see what JSON is and what data is represented in JSON format.

JSON stands for JavaScript Object Notation. JSON is a light-weight the text based format for data exchange. Using JSON Format You can pack the data of the 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 is placed in between the brackets. A property name and its value is enclosed in double quotes ("..."). A property and its value is separated by a colon (:). Multiple name-value pairs is delimited by a comma (,).

Using JSON format you essentially represent objects. In this respect JSON is quite similar to JavaScript objects. However, it's important to remember that although JavaScript objects and JSON objects look quite similar these S is not exactly the same. For example, JavaScript object properties can is enclosed in single quotes (' ... '), double quotes ("...") or you can omit Using quotes altogether. JSON format on the other hand requires your to enclose property names in double quotes.

The following code shows an object represented in JSON format:

var customer ={"CustomerID": "CompanyName": "Some Company", "ContactName": "Some             Name "," IsActive ": true; };

Once created, you can use the 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 T Hem in an alert dialog.

Alert (Customer.companyname + "-" + customer.) ContactName);
Understanding the problem

Now so you know basics of JSON format, let's look at the problem and dealing with dates. Since JSON doesn ' t has any special representation for dates; They is 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. Web Forms and MVC serializes dates in a special form-\/date (ticks) \-where ticks is the number of milliseconds since 1 January 1970.

Note:
The ASP. NET Web API uses ISO date format by default while serializing dates.

To understand the issue better, let's create an ASP. Application that sends order information including order date and shipping date to the client in JSON format. Begin by creating a new ASP. 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 a 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 can see the HomeController class have the GetOrder () action method. The GetOrder () method selects orders from the Orders table and returns the first order to the caller using the Firstordefa Ult () method. Notice how the Order object was 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. 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 has 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 is used to display RequiredDate and ShippedDate values.

If you invoke the method using a jQuery and look at the Order object using Chrome Developer tools, you'll see this:


Order Object Results

As can see all the dates is represented as \/date (ticks) \/. These dates cannot is consumed in JavaScript code in their the 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 so you know the problem with date serialization in ASP. NET MVC, let's see how to overcome it. One, possibly the simplest, the on-the-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

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 forma T. 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. The 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] 'll be 836418600000. Based on the 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:

tojavascriptdate (order. RequiredDate) + ", Shipped Date:" + tojavascriptdate (order. ShippedDate));};

Although the above example uses date in MM/DD/YYYY format, you be free to use any other format once a Date object is cons Tructed.

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 this 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 the "this task" need to create your own actionresult and then serialize the data the the-the-the-you want. As far as ASP. Applications is concerned, Json.NET (a popular library to work with Json in. NET applications) is Y Our best choice for serializing the data. Unlike the default serializer that comes with ASP. Json.NET serializes dates in ISO format.

To demonstrate how the server side technique can is implemented, add a Jsonnetresult class in your project that inherits F Rom 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 stre Am. The Jsonserializer class allows-serialize and deserialize objects in JSON format. The Serialize () method writes the Data object to the JsonTextWriter created earlier. The Data object is 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 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 it Data property was set to the Order object obtained from the Firstordefau Lt () method.

If you run the client side JQuery code again, this time you'll get dates in ISO date format. You can also confirm this using Chrome developer tools:


ISO Date Format

As can see all the dates is now returned as YYYY-MM-DDTHH:MM:SS format. To convert these date values into JavaScript are quite simple. Can simply pass them to date constructor and parse them into a date object like this:

var dt = new Date (order. Shippingdate);

Working with JSON date types in ASP MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.