Sunday, January 31, 2016

How to handle ASP.NET MVC JSON Result Date Format Issue

ASP.Net MVC controller will return JsonResult for action so that ajax can handle those Json data. But Json data has issues for type DateTime, especially Microsoft SQL Server DB. Here is some result if you just display those data in string format: "/Date(-501361200000)/". This is one very popular topic for ASP.Net MVC Json data processing. You can process those Json DateTime at client side using some Javascript tricks. But the best solution is on the Server side, you can use Json.Net from newtonsoft to do the magic.

This is one typical action method in controller:
        public JsonResult GetStudent(string name)
        {
            try
            {
                if (name == null)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    using (StudentService _service = new StudentService())
                    {
                        Student = _service.GetStudent(name);
                        return Json(model, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
You don't need to change above code. What you should do is:
First,  add a new class CustomJsonResult which inherits from JsonResult.
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class CustomJsonResult : JsonResult
{
    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 = "yyyy-MM-dd HH:mm:ss";
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}
Second, in your Base Controller, override Json method to return CustomJsonResult.
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }
Then all JsonResult call in your controller will return CustomJsonResult I created above, which use Newtonsoft.Json.Converters.IsoDateTimeConverter as serializer instead, and you will see the readable DateTime instead of annoying and wild date format in JsonResult.

Source:
http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

No comments:

Post a Comment