最近写个Web项目,C#+EasyUI ,数据库里定义了一个DateTime字段,DataGrid返回的日期格式是/Date(20130450000365)/,
,为了解决这个问题,在百度上搜了一些解决方案,在datagrid里加一个formatter,新建一个function方法,用来格式化被序列化的DateTime字段。
field: 'BIRTHDAY', title: '生日', width: 100,formatter: function (value, row, index)
{
return formatterDateTime(value)
}
function formatterDateTime(date) {
console.log(1);
if (date == undefined) {
return "";
}
/*json格式时间转js时间格式*/
date = date.substr(1, date.length - 2);
var obj = eval('(' + "{Date: new " + date + "}" + ')');
var date = obj["Date"];
if (date.getFullYear() < 1900) {
return "";
}
var datetime = date.getFullYear()
+ "-"// "年"
+ ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0"
+ (date.getMonth() + 1))
+ "-"// "月"
+ (date.getDate() < 10 ? "0" + date.getDate() : date
.getDate())
+ " "
+ (date.getHours() < 10 ? "0" + date.getHours() : date
.getHours())
+ ":"
+ (date.getMinutes() < 10 ? "0" + date.getMinutes() : date
.getMinutes())
+ ":"
+ (date.getSeconds() < 10 ? "0" + date.getSeconds() : date
.getSeconds());
return datetime;
}
到这里显示的问题就解决了,这个不算难,困扰我的是后面的反序列化,由于要将datagrid里的这个字段反序列化放到一个集合里面,但是结果老是报错,提示
/Date(20130450000365)/不是有效的DateTime字段,原来上面格式化的值只是解决了显示的问题,使用这个变量的时候还是原来格式化之前的值。最后发现实际上是Json格式化问题,我们应该在返回json的时候进行格式化,我们需要重写系统的JsonResult类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
namespace App.Common
{
public class ToJsonResult : JsonResult
{
const string error = "该请求已被封锁,因为敏感信息透露给第三方网站,这是一个GET请求时使用的。为了可以GET请求,请设置JsonRequestBehavior AllowGet。";
///
/// 格式化字符串
///
public string FormateStr
{
get;
set;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(error);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonstring = serializer.Serialize(Data);
//string p = @"\\/Date\((\d+)\+\d+\)\\/";
string p = @"\\/Date\(\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonstring = reg.Replace(jsonstring, matchEvaluator);
response.Write(jsonstring);
}
}
///
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
///
private string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
string p = @"\d";
var cArray = m.Value.ToCharArray();
StringBuilder sb = new StringBuilder();
Regex reg = new Regex(p);
for (int i = 0; i < cArray.Length; i++)
{
if (reg.IsMatch(cArray[i].ToString()))
{
sb.Append(cArray[i]);
}
}
// reg.Replace(m.Value;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(sb.ToString()));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
}
}
创建Controller的基类,BaseController,让Controller去继承BaseController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using App.Common;
using App.Models.Sys;
namespace App.Admin
{
public class BaseController : Controller
{
///
/// 获取当前用户Id
///
///
public string GetUserId()
{
if (Session["Account"] != null)
{
AccountModel info = (AccountModel)Session["Account"];
return info.Id;
}
else
{
return "";
}
}
///
/// 获取当前用户Name
///
///
public string GetUserTrueName()
{
if (Session["Account"] != null)
{
AccountModel info = (AccountModel)Session["Account"];
return info.TrueName;
}
else
{
return "";
}
}
///
/// 获取当前用户信息
///
/// 用户信息
public AccountModel GetAccount()
{
if (Session["Account"] != null)
{
return (AccountModel)Session["Account"];
}
return null;
}
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new ToJsonResult
{
Data = data,
ContentEncoding = contentEncoding,
ContentType = contentType,
JsonRequestBehavior = behavior,
FormateStr = "yyyy-MM-dd HH:mm:ss"
};
}
///
/// 返回JsonResult.24 ///
/// 数据
/// 行为
/// json中dateTime类型的格式
/// Json
protected JsonResult MyJson(object data, JsonRequestBehavior behavior, string format)
{
return new ToJsonResult
{
Data = data,
JsonRequestBehavior = behavior,
FormateStr = format
};
}
///
/// 返回JsonResult42 ///
/// 数据
/// 数据格式
/// Json
protected JsonResult MyJson(object data, string format)
{
return new ToJsonResult
{
Data = data,
FormateStr = format
};
}
///
/// 检查SQL语句合法性
///
///
///
public bool ValidateSQL(string sql, ref string msg)
{
if (sql.ToLower().IndexOf("delete") > 0)
{
msg = "查询参数中含有非法语句DELETE";
return false;
}
if (sql.ToLower().IndexOf("update") > 0)
{
msg = "查询参数中含有非法语句UPDATE";
return false;
}
if (sql.ToLower().IndexOf("insert") > 0)
{
msg = "查询参数中含有非法语句INSERT";
return false;
}
return true;
}
}
}
然后, 用你的Controller去继承该BaseController, public class EmptyOutController : BaseController。最后问题完美解决,使用这个后台控制的方法,js界面就不需要格式化了,显示也没有问题。