欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的方法

程序员文章站 2023-12-15 21:45:52
问题背景:            在使用asp.net mvc 结合j...

问题背景:

           在使用asp.net mvc 结合jquery esayui做一个系统,但是在使用使用this.json方法直接返回一个json对象,在列表中显示时发现datetime类型的数据在转为字符串是它默认转为date(84923838332223)的格式,在经过查资料发现使用前端来解决这个问题的方法不少,但是我又发现在使用jquery easyui时,加载列表数据又不能对数据进行拦截,进行数据格式转换之后再加载,后来发现可以通过自定义jsonresult实现,认为这种方法比较可行,就开始研究

我们先来看看jsonresult的源码

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

当我看到上面代码中的红色部分,我感到有些熟悉,心里比较高兴,以前使用过ashx来传json的都应该用过此方法吧

原来它也是使用这个方法进行序列化的。我们就可以在这个地方先获取到json序列化之后的字符串!然后做写“小动作”,就ok了

下面我就定义了一个自己的jsonresult了

/// <summary>
  /// 自定义json视图
  /// </summary>
  public class customjsonresult:jsonresult
  {
    /// <summary>
    /// 格式化字符串
    /// </summary>
    public string formatestr
    {
      get;
      set;
    }

    /// <summary>
    /// 重写执行视图
    /// </summary>
    /// <param name="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> 
    /// 将json序列化的时间由/date(1294499956278)转为字符串 .
    /// </summary> 
    /// <param name="m">正则匹配</param>
    /// <returns>格式化后的字符串</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;
    }
  }


在这里做的“小动作”就是红色部分,得到字符串以后,通过正则表达式的方式获得date(12347838383333)的字符串,然后把它转换为datetime类型,最后在转为我们想要的格式即可,这个格式可以使用formatestr属性设置。

剩下的就是使用我们自己定义的jsonresult来替换asp.net mvc默认的jsonresult的问题了,接着从源码中找答案,下面是controller类的部分代码

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

以上是controller类来实例化jsonresult的所有代码。我们只需写一个basecontroller类,重写最后一个方法即可,然后我们自己的controller在继承basecontroller即可

下面是basecontroller类的部分代码,我们为方便自己个性化的需要又定义了两个myjosn的方法

/// <summary>
    /// 返回jsonresult
    /// </summary>
    /// <param name="data">数据</param>
    /// <param name="contenttype">内容类型</param>
    /// <param name="contentencoding">内容编码</param>
    /// <param name="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>
    /// 返回jsonresult.24     /// </summary>
    /// <param name="data">数据</param>
    /// <param name="behavior">行为</param>
    /// <param name="format">json中datetime类型的格式</param>
    /// <returns>json</returns>
    protected jsonresult myjson(object data, jsonrequestbehavior behavior,string format)
    {
      return new customjsonresult
      {
        data = data,
        jsonrequestbehavior = behavior,
        formatestr = format
      };
    }

    /// <summary>
    /// 返回jsonresult42     /// </summary>
    /// <param name="data">数据</param>
    /// <param name="format">数据格式</param>
    /// <returns>json</returns>
    protected jsonresult myjson(object data, string format)
    {
      return new customjsonresult
      {
        data = data,
        formatestr = format
      };
    }

最后我们在自己的controller中调用即可

public class projectmilestonecontroller : basecontroller
  {
    /// <summary>
    /// 首页视图
    /// </summary>
    /// <returns>视图</returns>
    public actionresult index()
    {
      return this.view();
    }

    #region 项目里程碑查询

    /// <summary>
    /// 根据项目编号获取项目里程碑
    /// </summary>
    /// <param name="projectid">项目编号</param>
    /// <returns>项目里程碑</returns>
    public jsonresult getprojectmilestonebyprojectid(int projectid)
    {
      ilist<projectmilestone> projectmilestones = facadecontainer.get<iprojectmilestoneservice>().getprojectmilestonesbyprojectid(projectid);
      return this.myjson(projectmilestones, "yyyy.mm.dd");
    }

    #endregion
  }

原文地址:http://www.cnblogs.com/jerrywang1991

以上就是asp.net mvc返回jsonresult中datetime类型数据格式问题的解决方法,希望对大家的学习有所帮助。

上一篇:

下一篇: