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