Method to solve the problem of DateTime type data format in Asp. net Mvc returning JsonResult

  • 2021-07-24 10:50:50
  • OfStack

Background of the problem:

After using asp. net mvc combined with jquery esayui as a system, But when you use the this. json method to return an json object directly, When displayed in the list, it is found that the data of type datetime is converted to Date (84923838332223) by default when it is converted to string. After checking the data, I found that there are many methods to solve this problem by using the front end, but I found that when using jquery easyui, loading list data can not intercept the data, and then loading it after data format conversion. Later, I found that it can be realized by customizing JsonResult, and I thought this method was feasible, so I began to study it

Let's take a look at the source code of jsonResult first


public class JsonResult : ActionResult
  {
    public JsonResult()
    {
      this.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet;
    }
    
    public 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 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));
      }
    }
    
    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 above code, I feel a little familiar, the heart is more happy, before the use of ashx to json should have used this method

It turns out that it is also serialized using this method. We can get the string after json serialization at this place first! Then write "little moves" and it will be ok

Now I have defined my own JsonResult


/// <summary>
  ///  Customize Json View 
  /// </summary>
  public class CustomJsonResult:JsonResult
  {
    /// <summary>
    ///  Formatting string 
    /// </summary>
    public string FormateStr
    {
      get;
      set;
    }

    /// <summary>
    ///  Override the execution view 
    /// </summary>
    /// <param name="context"> Context </param>
    public override void ExecuteResult(ControllerContext context)
    {
      if (context == null)
      {
        throw new 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> 
    ///  Will Json The time of serialization is determined by the /Date(1294499956278) Convert to String  .
    /// </summary> 
    /// <param name="m"> Regular matching </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 trick" done here is the red part. After getting the string, get the string of Date (12347838383333) by regular expression, then convert it to DateTime type, and finally convert it to the format we want. This format can be set by using FormateStr attribute.

The rest is to replace asp with our own JsonResult. net mvc default JsonResult, and then find the answer from the source code. Here is part of the code of Controller class


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)
    {
      return this.Json(data, contentType, null, behavior);
    }
    
    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
      return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
    }

The above is the Controller class to instantiate all the code of JsonResult. We only need to write an BaseController class, override the last method, and then our own Controller inherits BaseController

The following is part of the code of BaseController class. We have defined two methods of MyJosn for our own personalized needs


/// <summary>
    ///  Return JsonResult
    /// </summary>
    /// <param name="data"> Data </param>
    /// <param name="contentType"> Content type </param>
    /// <param name="contentEncoding"> Content coding </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>
    /// <param name="behavior"> Behavior </param>
    /// <param name="format">json Medium dateTime Format of type </param>
    /// <returns>Json</returns>
    protected JsonResult MyJson(object data, JsonRequestBehavior behavior,string format)
    {
      return new CustomJsonResult
      {
        Data = data,
        JsonRequestBehavior = behavior,
        FormateStr = format
      };
    }

    /// <summary>
    ///  Return JsonResult42     /// </summary>
    /// <param name="data"> Data </param>
    /// <param name="format"> Data format </param>
    /// <returns>Json</returns>
    protected JsonResult MyJson(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 page view 
    /// </summary>
    /// <returns> View </returns>
    public ActionResult Index()
    {
      return this.View();
    }

    #region  Project Milestone Query 

    /// <summary>
    ///  Obtain project milestones according to project number 
    /// </summary>
    /// <param name="projectId"> Item number </param>
    /// <returns> Project Milestones </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 return JsonResult DateTime type data format problem solution, I hope to help you learn.


Related articles: