A method to resolve the problem of datetime type data format problems in asp.net mvc return Jsonresult-practical tips

Source: Internet
Author: User
Tags httpcontext serialization string format

Problem background:

When using asp.net mvc to make a system with jquery Esayui, but when using the This.json method to return a JSON object directly, it is found in the list that the datetime type of data is converted to a string as it defaults to date ( 84923838332223 format, in the search for data found using the front-end to solve this problem, but I also found that when using jquery Easyui, loading list data can not intercept data, data format conversion before loading, Later found that the implementation of the custom jsonresult can be realized, that this method is more feasible, began to study

Let's take a look at Jsonresult's source.

public class Jsonresult:actionresult {public Jsonresult () {this.
    Jsonrequestbehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet;
        override void Executeresult (ControllerContext context) {if (context = null) {
      throw new ArgumentNullException ("context"); } if (this. Jsonrequestbehavior = = System.Web.Mvc.JsonRequestBehavior.DenyGet) && string. Equals (context. HttpContext.Request.HttpMethod, "get", StringComparison.OrdinalIgnoreCase)) {throw new Invalidoperationexce
      Ption (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));
    
    } public Encoding contentencoding {get; set;}
    
    public string ContentType {get; set;}
    
    Public object Data {get; set;}
  Public System.Web.Mvc.JsonRequestBehavior Jsonrequestbehavior {get; set;} }
}

When I see the red part of the code above, I feel a little familiar, I am happy, I used to use ASHX to pass the JSON should use this method

It turns out that it's also serialized using this method. We can get the string after JSON serialization first in this place! And then write "little gestures", OK.

Now I've defined one of my own jsonresult.

<summary>///Custom JSON view///</summary> public class Customjsonresult:jsonresult {///<sum
      mary>///format string///</summary> public string Formatestr {get;
    Set
    ///<summary>///Override execution View///</summary>///<param name= "context" > Contextual </param> public override void Executeresult (ControllerContext context) {if (context = = null) {throw NE
      W ArgumentNullException ("context"); } 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 JSS = new JavaScriptSerializer ();  String jsonstring = JSS.
        Serialize (Data);
        String p = @ "\\/date\ ((\d+) \) \\/"; MatchEvaluator matchevaluator = new MatchEvaluator (this.
        convertjsondatetodatestring);
        Regex reg = new regex (p); jsonstring = Reg.

        Replace (jsonstring, MatchEvaluator); Response.
      Write (jsonstring);
    }///<summary>///converts the JSON serialization time from/date (1294499956278) to a string.
    </summary>///<param name= "M" > regular match </param>///<returns> formatted string </returns> private String convertjsondatetodatestring (Match m) {string result = string.
      Empty;
      DateTime dt = new DateTime (1970, 1, 1); DT = dt. Addmilliseconds (Long. Parse (M.groups[1].
      Value)); DT = dt.
      ToLocalTime (); result = dt.
      ToString (FORMATESTR);
    return result;
 }
  }


The "little gestures" here are the red ones, and after we get the string, we get the string of date (12347838383333) through the regular expression, and then we convert it to the datetime type, and finally to the format we want, This format can be set using the Formatestr property.

The rest is to use our own defined jsonresult to replace the asp.net MVC default Jsonresult problem, and then find the answer from the source, the following is part of the Controller class code

protected internal Jsonresult Json (object data) {return this.
    Json (data, NULL, NULL, jsonrequestbehavior.denyget); } protected internal Jsonresult Json (object data, String contentType) {return this.
    Json (data, ContentType, NULL, jsonrequestbehavior.denyget); } protected internal Jsonresult Json (object data, Jsonrequestbehavior behavior) {return this.
    Json (data, NULL, NULL, behavior);
      Protected internal virtual Jsonresult Json (object data, String ContentType, Encoding contentencoding) { return this.
    Json (data, ContentType, contentencoding, Jsonrequestbehavior.denyget); protected internal Jsonresult Json (object data, String contentType, Jsonrequestbehavior behavior) {R Eturn this.
    Json (data, contentType, NULL, behavior); Protected internal virtual Jsonresult Json (object data, String ContentType, Encoding contentencoding, Jsonreque Stbehavior behavior) {returnNew Jsonresult {data = data, ContentType = ContentType, contentencoding = contentencoding, Jsonrequestbehavior = behavior
    }; }

The above is the Controller class to instantiate all the code for the Jsonresult. We just write a Basecontroller class, rewrite the last method, and then our own controller inherits Basecontroller

Here are some of the code for the Basecontroller class, and we define two myjosn for the convenience of our personalized needs

<summary>///back Jsonresult///</summary>///<param name= "Data" > Data </param>/ <param name= "ContentType" > Content type </param>///<param name= "contentencoding" > Content encoding </param>/ <param name= "Behavior" > Behavior </param>///<returns>JsonReuslt</returns> 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, formatestr = "Yyyy-mm-dd HH:mm:ss"}; ///<summary>///return jsonresult.24///</summary>///<param name= "Data" > Data </param&
    Gt
    <param name= "Behavior" > Behavior </param>///<param name= "format" >json formats for datetime types </param> <returns>json</returns> protected Jsonresult Myjson (object data, Jsonrequestbehavior behavior,string format) {Retu
      RN New Customjsonresult {data = data, Jsonrequestbehavior = behavior, formatestr = format
    }; ///<summary>///return JsonResult42///</summary>///<param name= "Data" > Data &LT;/PARAM&G
    T <param name= "format" > Data format </param>///<returns>Json</returns> protected Jsonresult Myj Son (object data, string format) {return new Customjsonresult {data = data, Formatestr =
    Format};
 }

Finally, we can call it in our own controller.

public class Projectmilestonecontroller:basecontroller
  {
    ///<summary>
    ///Home View
    ///</ summary>
    ///<returns> view </returns> public
    ActionResult Index () {return this
      . View ();
    }

    #region Project Milestones Query

    ///<summary>
    ///get project milestones based on project number
    ///</summary>
    ///<param name= " ProjectID "> Project number </param>
    ///<returns> Project milestone </returns> Public
    Jsonresult Getprojectmilestonebyprojectid (int projectid)
    {
      ilist<projectmilestone> projectmilestones = Facadecontainer.get<iprojectmilestoneservice> (). Getprojectmilestonesbyprojectid (ProjectID);
      return this. Myjson (Projectmilestones, "yyyy.") Mm.dd ");
    }

    #endregion
  }

Original address: http://www.cnblogs.com/JerryWang1991

The above is asp.net mvc returns the Jsonresult in the DateTime type data format problem solution, hoped that has the help to everybody's study.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.