Some help I'm bringing with asp.net mvc the tables I call it with ajax
JSON does not have a date data type and the default .net serializer converts DateTime
to that format you see in the form of string . You have some alternatives to deal with that:
You handle it in JavaScript
When you receive the data in your ajax call, you deserialize it in this way:
var data = JSON.parse(data, function(key, value) {
if (typeof value === 'string') {
var d = /\/Date\((\d*)\)\//.exec(value);
return (d) ? new Date(+d[1]) : value;
}
return value;
});
the function parse
optionally receives a function as the second parameter that allows you to control how to interpret the data. In this example, you use a regex to identify the strings that are date formatted.
You format it in the controller before serializing
Instead of sending properties DateTime
, you create another object that has a string
with the date in the format you want. You have not shown us the code of the action that sends the data, if you added it, it would be easier to indicate how to do it.
You use an alternate serializer
With a little configuration you can Json.NET library that is more flexible and allows you to choose how the dates will be serialized, in Microsoft format ( /Date(1542333807388)/
) or ISO ( 2018-11-16T02:03:27.388Z
).
You create a class derived from JsonResult
:
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
and then in the controller you use it like this:
[HttpGet]
public ActionResult Index() {
return new CustomJsonResult { Data = new { fecha = DateTime.Now } };
}