• JSONResult引用某博客


    http://www.cnblogs.com/JerryWang1991/archive/2013/03/08/2950457.html

    最近开始用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还有很多好玩的特性,大家一起摸索吧!

  • 相关阅读:
    javascript 犀牛书
    Hmtl/css
    SQL Server 查询中使用Union或Union All后Order by排序无效(嵌套查询乱序)
    CSS 动画
    CSS 文字排版
    CSS 太极图
    Amazon Products 服务费估算
    CSS3 结构伪类选择器
    JS 执行机制
    vue 生命周期函数的学习
  • 原文地址:https://www.cnblogs.com/kexb/p/4538955.html
Copyright © 2020-2023  润新知