问题背景:
在使用asp.net mvc 结合jquery esayui做一个系统,但是在使用使用this.json方法直接返回一个json对象,在列表中显示时发现datetime类型的数据在转为字符串是它默认转为Date(84923838332223)的格式,在经过查资料发现使用前端来解决这个问题的方法不少,但是我又发现在使用jquery easyui时,加载列表数据又不能对数据进行拦截,进行数据格式转换之后再加载,后来发现可以通过自定义JsonResult实现,认为这种方法比较可行,就开始研究
我们先来看看jsonResult的源码
public class JsonResult : ActionResult
{
public JsonResult()
{
this.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((this.JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(this.Data));
}
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public System.Web.Mvc.JsonRequestBehavior JsonRequestBehavior { get; set; }
}
}
当我看到上面代码中的红色部分,我感到有些熟悉,心里比较高兴,以前使用过ashx来传json的都应该用过此方法吧
原来它也是使用这个方法进行序列化的。我们就可以在这个地方先获取到json序列化之后的字符串!然后做写“小动作”,就ok了
下面我就定义了一个自己的JsonResult了
/// <summary>
/// 自定义Json视图
/// </summary>
public class CustomJsonResult:JsonResult
{
/// <summary>
/// 格式化字符串
/// </summary>
public string FormateStr
{
get;
set;
}
/// <summary>
/// 重写执行视图
/// </summary>
/// <param name="context">上下文</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsonString = jss.Serialize(Data);
string p = @"\\/Date\((\d+)\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
response.Write(jsonString);
}
}
/// <summary>
/// 将Json序列化的时间由/Date(1294499956278)转为字符串 .
/// </summary>
/// <param name="m">正则匹配</param>
/// <returns>格式化后的字符串</returns>
private string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString(FormateStr);
return result;
}
}
在这里做的“小动作”就是红色部分,得到字符串以后,通过正则表达式的方式获得Date(12347838383333)的字符串,然后把它转换为DateTime类型,最后在转为我们想要的格式即可,这个格式可以使用FormateStr属性设置。
剩下的就是使用我们自己定义的JsonResult来替换asp.net mvc默认的JsonResult的问题了,接着从源码中找答案,下面是Controller类的部分代码
protected internal JsonResult Json(object data)
{
return this.Json(data, null, null, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, string contentType)
{
return this.Json(data, contentType, null, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
return this.Json(data, null, null, behavior);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
return this.Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
{
return this.Json(data, contentType, null, behavior);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };
}
以上是Controller类来实例化JsonResult的所有代码。我们只需写一个BaseController类,重写最后一个方法即可,然后我们自己的Controller在继承BaseController即可
下面是BaseController类的部分代码,我们为方便自己个性化的需要又定义了两个MyJosn的方法
/// <summary>
/// 返回JsonResult
/// </summary>
/// <param name="data">数据</param>
/// <param name="contentType">内容类型</param>
/// <param name="contentEncoding">内容编码</param>
/// <param name="behavior">行为</param>
/// <returns>JsonReuslt</returns>
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new CustomJsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding =contentEncoding,
JsonRequestBehavior = behavior,
FormateStr = "yyyy-MM-dd HH:mm:ss"
};
}
/// <summary>
/// 返回JsonResult.24 /// </summary>
/// <param name="data">数据</param>
/// <param name="behavior">行为</param>
/// <param name="format">json中dateTime类型的格式</param>
/// <returns>Json</returns>
protected JsonResult MyJson(object data, JsonRequestBehavior behavior,string format)
{
return new CustomJsonResult
{
Data = data,
JsonRequestBehavior = behavior,
FormateStr = format
};
}
/// <summary>
/// 返回JsonResult42 /// </summary>
/// <param name="data">数据</param>
/// <param name="format">数据格式</param>
/// <returns>Json</returns>
protected JsonResult MyJson(object data, string format)
{
return new CustomJsonResult
{
Data = data,
FormateStr = format
};
}
最后我们在自己的Controller中调用即可
public class ProjectMileStoneController : BaseController
{
/// <summary>
/// 首页视图
/// </summary>
/// <returns>视图</returns>
public ActionResult Index()
{
return this.View();
}
#region 项目里程碑查询
/// <summary>
/// 根据项目编号获取项目里程碑
/// </summary>
/// <param name="projectId">项目编号</param>
/// <returns>项目里程碑</returns>
public JsonResult GetProjectMileStoneByProjectId(int projectId)
{
IList<ProjectMileStone> projectMileStones = FacadeContainer.Get<IProjectMileStoneService>().GetProjectMileStonesByProjectId(projectId);
return this.MyJson(projectMileStones, "yyyy.MM.dd");
}
#endregion
}
原文地址:http://www.cnblogs.com/JerryWang1991
以上就是Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的解决方法,希望对大家的学习有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。