最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決Asp.net Mvc返回JsonResult中DateTime類型數(shù)據(jù)格式問題的方法

 更新時間:2016年06月03日 10:42:31   作者:wangyan9110  
這篇文章主要介紹了解決Asp.net Mvc返回JsonResult中DateTime類型數(shù)據(jù)格式問題的方法,需要的朋友可以參考下

問題背景:

           在使用asp.net mvc 結(jié)合jquery esayui做一個系統(tǒng),但是在使用使用this.json方法直接返回一個json對象,在列表中顯示時發(fā)現(xiàn)datetime類型的數(shù)據(jù)在轉(zhuǎn)為字符串是它默認轉(zhuǎn)為Date(84923838332223)的格式,在經(jīng)過查資料發(fā)現(xiàn)使用前端來解決這個問題的方法不少,但是我又發(fā)現(xiàn)在使用jquery easyui時,加載列表數(shù)據(jù)又不能對數(shù)據(jù)進行攔截,進行數(shù)據(jù)格式轉(zhuǎn)換之后再加載,后來發(fā)現(xiàn)可以通過自定義JsonResult實現(xiàn),認為這種方法比較可行,就開始研究

我們先來看看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>
    /// 重寫執(zhí)行視圖
    /// </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)轉(zhuǎn)為字符串 .
    /// </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)的字符串,然后把它轉(zhuǎn)換為DateTime類型,最后在轉(zhuǎn)為我們想要的格式即可,這個格式可以使用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類的部分代碼,我們?yōu)榉奖阕约簜€性化的需要又定義了兩個MyJosn的方法

/// <summary>
    /// 返回JsonResult
    /// </summary>
    /// <param name="data">數(shù)據(jù)</param>
    /// <param name="contentType">內(nèi)容類型</param>
    /// <param name="contentEncoding">內(nèi)容編碼</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">數(shù)據(jù)</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">數(shù)據(jù)</param>
    /// <param name="format">數(shù)據(jù)格式</param>
    /// <returns>Json</returns>
    protected JsonResult MyJson(object data, string format)
    {
      return new CustomJsonResult
      {
        Data = data,
        FormateStr = format
      };
    }

最后我們在自己的Controller中調(diào)用即可

public class ProjectMileStoneController : BaseController
  {
    /// <summary>
    /// 首頁視圖
    /// </summary>
    /// <returns>視圖</returns>
    public ActionResult Index()
    {
      return this.View();
    }

    #region 項目里程碑查詢

    /// <summary>
    /// 根據(jù)項目編號獲取項目里程碑
    /// </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類型數(shù)據(jù)格式問題的解決方法,希望對大家的學習有所幫助。

相關(guān)文章

  • .Net Core2.1 WebAPI新增Swagger插件詳解

    .Net Core2.1 WebAPI新增Swagger插件詳解

    這篇文章主要給大家介紹了關(guān)于.Net Core2.1 WebAPI新增Swagger插件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-07-07
  • Asp.Net實現(xiàn)404頁面與301重定向的方法

    Asp.Net實現(xiàn)404頁面與301重定向的方法

    這篇文章主要介紹了Asp.Net實現(xiàn)404頁面與301重定向的方法,較為詳細的分析了404頁面的原理與針對404錯誤與301跳轉(zhuǎn)的實現(xiàn)方法,是非常實用的技巧,需要的朋友可以參考下
    2014-11-11
  • ASP.net基礎知識之常見錯誤分析

    ASP.net基礎知識之常見錯誤分析

    ASP.net基礎知識之常見錯誤分析...
    2007-07-07
  • Entity?Framework導航屬性介紹

    Entity?Framework導航屬性介紹

    這篇文章介紹了Entity?Framework的導航屬性,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • .Net?Core使用Coravel實現(xiàn)任務調(diào)度的完整步驟

    .Net?Core使用Coravel實現(xiàn)任務調(diào)度的完整步驟

    最近在使用調(diào)度程序創(chuàng)建簡單的服務,該服務將執(zhí)行一些重復的IO操作,使用的是Coravel調(diào)度庫,下面這篇文章主要給大家介紹了關(guān)于.Net?Core使用Coravel實現(xiàn)任務調(diào)度的完整步驟,需要的朋友可以參考下
    2022-08-08
  • 詳解ASP.NET Core 2.0 視圖引擎(譯)

    詳解ASP.NET Core 2.0 視圖引擎(譯)

    本篇文章主要介紹了詳解ASP.NET Core 2.0 視圖引擎(譯),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • .NET Core配置多環(huán)境的方法步驟

    .NET Core配置多環(huán)境的方法步驟

    配置多環(huán)境是日常開發(fā)經(jīng)常需要用到的操作,實現(xiàn)多環(huán)境配置后可以規(guī)避生產(chǎn)測試環(huán)境混合帶來的麻煩和風險,這篇文章主要介紹了.NET Core配置多環(huán)境的方法步驟,感興趣的小伙伴們可以參考一下
    2019-03-03
  • .net數(shù)據(jù)庫操作框架SqlSugar的簡單入門

    .net數(shù)據(jù)庫操作框架SqlSugar的簡單入門

    這篇文章主要介紹了.net數(shù)據(jù)庫操作框架SqlSugar的簡單入門,幫助大家更好的理解和學習使用.net技術(shù),感興趣的朋友可以了解下
    2021-04-04
  • VS2015 Update2 構(gòu)建 Android 程序問題匯總

    VS2015 Update2 構(gòu)建 Android 程序問題匯總

    這篇文章主要介紹了VS2015 Update2 構(gòu)建 Android 程序問題匯總的相關(guān)資料,需要的朋友可以參考下
    2016-07-07
  • ASP.NET?Core實時庫SignalR簡介及使用

    ASP.NET?Core實時庫SignalR簡介及使用

    這篇文章介紹了ASP.NET?Core實時庫SignalR簡介及使用方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-01-01

最新評論

定远县| 宜宾县| 永城市| 龙州县| 鄄城县| 贞丰县| 称多县| 南投县| 玛多县| 锦屏县| 从化市| 自治县| 麻栗坡县| 涞源县| 襄垣县| 伊吾县| 堆龙德庆县| 荆门市| 晋中市| 蒲城县| 道孚县| 开平市| 兖州市| 长葛市| 乐清市| 清流县| 定日县| 安多县| 庐江县| 福建省| 建瓯市| 罗田县| 元氏县| 正安县| 岳阳市| 精河县| 太和县| 东阿县| 雷山县| 清水县| 清流县|