最简单的处理MVC中默认的Json方法返回时间的问题

来源:互联网 发布:web前端面试题知乎 编辑:程序博客网 时间:2024/06/14 16:49

利用 Json方法返回 数据时,如果有时间格式,会变成 “\/Date(1369419656217)\/” 这个样子,问了同事找到个解决方法

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

var timeConverter = new IsoDateTimeConverter { DateTimeFormat = “yyyy-MM-dd HH:mm:ss” };

return Content(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));
我们把这个方法封装一下,写到Controller的基类里,创建一个 BaseController 的基类

public class BaseController : Controller
{
///
/// 返回处理过时间的json
///
///
///
protected ContentResult JsonDate(object Data)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = “yyyy-MM-dd HH:mm:ss” };

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

保证我们每一个Controller去继承这个类

复制代码
public class HomeController : BaseController
{

    public ActionResult GetJson()    {

var result = new object[] {
  new { name = “linfei”, age = “22”, address = “wuhan”,date=”2013-05-01” },
  new { name = “linfei”, arg = “26”, address = “sh”,date=”2013-05-20” }
};

return JsonDate(result);
}
}

0 0
原创粉丝点击