zoukankan      html  css  js  c++  java
  • 关于ASP.NET MVC 中JsonResult返回的日期值问题

    最近开始用MVC做项目,在使用 JsonResult返回数据的时候,日期被反射成了/Date 1233455这种格式,遍查网上都是在客户端使用JS来处理这个问题的,这样的话,就需要在每一个涉及到日期的地方都做一次转换后,才能用来使用。

      于是我通过反编译Controller抽象类以及JsonResult类后发现:

      jsonresult中处理对象到JSON字符串的方法:

        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));
            }
        }

    在这个方法里使用的是JavaScriptSerializer这个来序列化对象到JSON。

    于是我自定义了一个类,继承JSONRESULT类

    并将上面的方法从写 ,用newton.json替换javascriptSerializer

    替换代码如下:

    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序列化。

    然后再重新定义一个Controller,命名为 JsonController,且设置为抽象类。

    然后重写方法:

    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
    }
    

    将 JsonResult改为我们继承JSONResult并重写了ExecuteResult方法的类,就大工告成了!

     以后只要JsonResult涉及到返回日期的,就可以让控制器继承我们自定义的这个类,由此解决日期问题。

    以上只解决了日期JSON后在JS中使用显示的问题,未解决日期参与运算的问题,但是根据我目前的经历,JS中日期参与预算的时间还比较少,所以能解决用于显示的问题,就很OK了,

    ASP.NET MVC还有很多好玩的特性,大家一起摸索吧!

  • 相关阅读:
    《剑指offer》面试题7:旋转数组的最小数字
    eclipse ------ TODO、FIXME、XXX 等任务标记
    RT-Thread ------ waitqueue
    RT-Thread ------ 设备注册
    ubuntu 安装 glibc
    openwrt上面移植MQTT代码
    MH5000-31模组无法识别SIM卡
    "Hello osmdroid World"手机GPS轨迹数据
    地质数据下载
    绘图软件Surfer绘制等高线
  • 原文地址:https://www.cnblogs.com/chongsha/p/7068908.html
Copyright © 2011-2022 走看看