Recently, MVC was used as a project. When jsonresult is used to return data, the date is reflected in the format of/date 1233455. On the internet, JavaScript is used on the client to handle this problem, in this way, it is necessary to make a conversion in every place involving the date before it can be used.
So after decompiling the Controller abstract class and jsonresult class, I found that:
Method for processing object to JSON string in jsonresult:
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); response.Write(serializer.Serialize(this.Data)); } }
In this method, javascriptserializer is used to serialize the object to JSON.
So I customized a class that inherits the jsonresult class.
Replace the preceding method with Newton. JSON with javascriptserializer.
The replacement code is as follows:
if (this.Data != null) { IsoDateTimeConverter timeFormat = new IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; response.Write(JsonConvert.SerializeObject(this.Data, Newtonsoft.Json.Formatting.Indented, timeFormat, x);); }
JSON serialization of the date is processed in this way.
Then define a controller, name it jsoncontroller, and set it as an abstract class.
Then rewrite the method:
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior){ return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };} |
Change jsonresult to the class that inherits jsonresult and overwrites the executeresult method!
In the future, as long as jsonresult involves the return date, the controller can inherit the custom class to solve the date problem.
The above only solves the problem of displaying in JS after date JSON, but does not solve the problem of date involved in calculation, but according to my current experience, in JS, the time spent on the date budget is relatively small, so it is okay to solve the problem of display,
ASP. net mvc has many other interesting features. Let's explore them together!