Currently the web methods or most of the methods in classic asp .net serializes using system.web.script.serialization.javascriptserializer class and this returns the javascript object's datetime members with values such as
"/Date(number of ticks)/"
. I understand this is an infamous problem and most people suggest using some kind of converters after we receive the data or return the data as string instead of objects.
For example the class
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
public DateTime DOB { get; set; }
}
if returned via a System.Web.Services.WebMethod with a [ScriptMethod(ResponseFormat = ResponseFormat.Json)] decoration, the response will be returned as below in result.d
{Name:"Steve", Age:30, DOB:"/Date(1249335477787)/"};
And we need to apply some code to convert the DOB into ISO format or some other acceptable format.
But I am just trying to see if some one has done some kind of response tweaking or using an over-ridden class to return the DateTime values from web methods. Is there a way to over-ride the javascriptserializer's functionality and use it in asp .net web methods so that it returns the date directly in ISO format? I am aware that it can be done in asp .net MVC in a few ways.
Is the same can be done in asp .net web form's web methods? That would save a lot of code and bugs as well :)
JSON format does not have a special type for dates. So dates have to be represented in JSONs as numbers of milliseconds or as strings. If dates are formatted as strings, the developer can read them.
The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. Time values are measured in 100-nanosecond units called ticks.
You can use this to get a date from JSON: var date = eval(jsonDate. replace(/\/Date\((\d+)\)\//gi, "new Date($1)")); And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.
Within the application memory, the state of an object resides in complicated data structures which is unsuitable for storage or exchange over the network. So, serialization converts the object into a shareable format. With serialization, we can transfer objects: Between client and server via REST APIs or GRPC.
I found a trick from http://blog.icanmakethiswork.io/2012/04/beg-steal-or-borrow-decent-javascript.html.
This is to replace the JsonSerializer's own date serializer and use the custom date serializer.
This is able to return me back a ISO formatted date time and I am also able to pass this inside moment js for manipulations inside javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With