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>

原文地址:https://www.cnblogs.com/kexb/p/4783628.html