相思资源网 Design By www.200059.com

问题背景:

           在使用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类型数据格式问题的解决方法,希望对大家的学习有所帮助。

标签:
Asp.net,Mvc,JsonResult,DateTime,格式

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

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

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