• mvc json 日期问题的最简单解决方法


    1.首先编写BaseController这个类,需要引入Newtonsoft.Json.dll程序集

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using WebApplication4.Models;

    namespace WebApplication4.Controllers
    {
    public class BaseController : Controller
    {
    protected new ContentResult Json(object Data,string format)
    {
    //"yyyy-MM-dd HH:mm:ss"
    var timeConverter = new IsoDateTimeConverter();
    timeConverter.DateTimeFormat = format;

    return Content(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));
    }


    }
    }

    2.其次继承BaseController这个类 return Json(data, "yyyy-MM-dd HH:mm:ss")的时候指定格式

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    using WebApplication4.Models;

    namespace WebApplication4.Controllers
    {

    public class HomeController : BaseController
    {
    // GET: Home
    public ActionResult Index()
    {
    ViewData.Model=new User() {Age = 18,CreateDate = DateTime.Now,Name = "张三"};
    return View();
    }

    public ActionResult ProcessDate()
    {
    var data = new {Name = "李四", CreateDate = DateTime.Now};
    return Json(data,"yyyy-MM-dd HH:mm:ss");
    //return Json(data, "yyyy-MM-dd HH:mm:ss");

    }
    }
    }

    3.接下来是前台页面的东西很简单data = JSON.parse(data)


    @{
    ViewBag.Title = "Index";
    }
    @model WebApplication4.Models.User
    <head>
    <title>json返回的日期处理</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    $(function() {
    alert(123);
    $("#btn_date_").click(function() {
    $.post("/Home/ProcessDate", function (data) {
    data = JSON.parse(data);
    alert("name=" + data.Name + "CreateDate=" + data.CreateDate);
    $("#name").html(data.Name);
    $("#date").html(data.CreateDate);

    });
    });
    })
    </script>
    </head>
    <h2>Index</h2>
    <h3>@Model.Name</h3>
    <br>
    <h3>@Model.CreateDate</h3>
    <br>
    <div>
    <a href="#" id="btn_date_">点击返回json日期</a>
    </div>
    <br/>
    <span>名称</span><span id="name"></span>
    <span>日期</span><span id="date"></span>

  • 相关阅读:
    机器学习回顾篇(14):主成分分析法(PCA)
    Elasticsearch系列---前缀搜索和模糊搜索
    Elasticsearch系列---近似匹配
    Elasticsearch系列---多字段搜索
    Elasticsearch系列---深入全文搜索
    Elasticsearch系列---shard内部原理
    Elasticsearch系列---结构化搜索
    01、Spring环境搭建
    02、Hibernate开发步骤
    01、Hibernate安装配置
  • 原文地址:https://www.cnblogs.com/kexb/p/4783628.html
Copyright © 2020-2023  润新知