利用 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 { /// <summary> /// 返回处理过时间的json /// </summary> /// <param name="Data"></param> /// <returns></returns> 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); }
}