本文转自:http://blog.163.com/luckcq@yeah/blog/static/17174770720121293437119/

最近项目中前台页面使用EasyUI的jQuery插件开发中遇到,EasyUI Form中的Datebox组件绑定ASP.NET MVC返回的DateTime类型的数据错误,因为ASP.NET MVC返回的DateTime类型的JsonResult的结果中的值是"\/Date(277630788015)\/",于是EasyUI显示的就是返回的值,没有将日期转换,直接显示在DateBox组件中,解决这个问题其实有两种办法:

  1. 扩展EasyUI的datebox组件的parser函数自定义格式化日期格式,不过存在一个问题是如果使用form.load数据是先将值赋给datebox不会调用datebox的parser方法,只有在加载完form后再改变datebox的值为”2011-11-3”格式的值;
  2. 第二种方式就是本文要讲得修改ASP.NET MVC的Json序列化方法,也就是修改JsonResult的序列化方法,下面就来详细说下这种方法。

首先看下ASP.NET MVC中的Controller的 Json方法的源码:

protected internal JsonResult Json(object data) {

return Json(data, null /* contentType */);

}

protected internal JsonResult Json(object data, string contentType) {

return Json(data, contentType, null /* contentEncoding */);

}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding) {

return new JsonResult {

Data = data,

ContentType = contentType,

ContentEncoding = contentEncoding

};

}

可以看出关键还是在JsonResult这个结果类中,JsonResult类的源码如下:

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]

public class JsonResult : ActionResult {

public Encoding ContentEncoding {

get;

set;

}

public string ContentType {

get;

set;

}

public object Data {

get;

set;

}

public override void ExecuteResult(ControllerContext context) {

if (context == null) {

throw new ArgumentNullException("context");

}

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) {

#pragma warning disable 0618

JavaScriptSerializer serializer = new JavaScriptSerializer();

response.Write(serializer.Serialize(Data));

#pragma warning restore 0618

}

}

}

}

看到这里大家应该明确我们的修改目标了,对,就是ExecuteResult这个方法,这个方法是序列化Data对象为Json格式的,可见ASP.NET MVC 使用的是System.Web.Script.Serialization.JavaScriptSerializer类

既然明确了目标,那么就开始动手吧。

1. 扩展JsonResult类自定义个CustomJsonResult类,重写ExecuteResult方法代码如下:

public class CustomJsonResult:JsonResult

{

public override void ExecuteResult(ControllerContext context)

{

if (context == null)

{

throw new ArgumentNullException("context");

}

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)

{

#pragma warning disable 0618

response.Write(JsonConvert.SerializeObject(Data));

#pragma warning restore 0618

}

}

我们使用的是Newtonsoft.Json.JsonConvert类序列化对象为Json的,具体集中.NET中的序列化对比可以参考文章:在.NET使用JSON作为数据交换格式

  1. 扩展Controller重写Json方法,代码如下:

public class BaseController:Controller

{

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)

{

return new CustomJsonResult

{

Data = data,

ContentType = contentType,

ContentEncoding = contentEncoding

};

}

}

下面就是我们实际使用方法了,因为Newtonsoft.Json.JsonConvert类DateTime类型可以指定序列化日期的类型为: [JsonConverter(typeof(IsoDateTimeConverter))], [JsonConverter(typeof(JavaScriptDateTimeConverter))]

[JsonConverter(typeof(IsoDateTimeConverter))]序列化后的格式为:1981-03-16T00:20:12.1875+08:00

[JsonConverter(typeof(JavaScriptDateTimeConverter))]序列化后的格式为:new Date(-277630787812)

于是我们指定实体类的DateTime属性为IsoDateTimeConverter,代码如下:

[Field("P_Date", "更新日期")]

[JsonConverter(typeof(IsoDateTimeConverter))]

public DateTime P_Date { get; set; }

控制器继承自BaseController,Action的返回结果还是JsonResult格式,代码如下:

public class GoodsController:BaseController

{

public JsonResult List(string page, string rows)

{

Page thepage = new Page() { PageSize = 20, CurrentPage = 1 };

if (!String.IsNullOrEmpty(rows))

{

thepage.PageSize = Convert.ToInt32(rows);

}

if (!String.IsNullOrEmpty(page))

{

thepage.CurrentPage = Convert.ToInt32(page);

}

Dictionary<string, object> result = new Dictionary<string, object>();

result.Add("rows", new BusinessLogic().SelectByPage<GoodsList>(ref thepage));

result.Add("total", thepage.SumCount);

return Json(result);

}

}

转载于:https://www.cnblogs.com/freeliver54/p/4383676.html

[转]自定义ASP.NET MVC JsonResult序列化结果相关推荐

  1. 自定义ASP.NET MVC JsonResult序列化结果

    最近项目中前台页面使用EasyUI的jQuery插件开发中遇到,EasyUI Form中的Datebox组件绑定ASP.NET MVC返回的DateTime类型的数据错误,因为ASP.NET MVC返 ...

  2. [转]自定义ASP.NET MVC Html辅助方法

    本文转自:http://www.cnblogs.com/myshell/archive/2010/05/09/1731269.html 在ASP.NET MVC中,Html辅助方法给我们程序员带来很多 ...

  3. 【小技巧】自定义asp.net mvc的WebFormViewEngine修改默认的目录结构

    先看一下我的解决方案的目录结构吧--- 一:先把Controller程序提取出来 默认的情况是所有的****Controller.cs文件都会放在Web程序集下的一个叫Controllers的文件夹下 ...

  4. Asp.net MVC JsonResult 忽略属性

    指定 JavaScriptSerializer 不序列化公共属性或公共字段.无法继承此类. 命名空间:  System.Web.Script.Serialization 程序集:  System.We ...

  5. 解决Asp.net Mvc返回JsonResult中DateTime类型数据格式的问题

    问题背景: 在使用asp.net mvc 结合jquery esayui做一个系统,但是在使用使用this.json方法直接返回一个json对象,在列表中显示时发现datetime类型的数据在转为字符 ...

  6. ASP.NET MVC 自定义路由中几个需要注意的小细节

    本文主要记录在ASP.NET MVC自定义路由时,一个需要注意的参数设置小细节. 举例来说,就是在访问 http://localhost/Home/About/arg1/arg2/arg3 这样的自定 ...

  7. ASP.NET MVC - 设置自定义IIdentity或IPrincipal

    我需要做一些相当简单的事情:在我的ASP.NET MVC应用程序中,我想设置一个自定义IIdentity / IPrincipal. 哪个更容易/更合适. 我想扩展默认值,以便我可以调用User.Id ...

  8. ASP.net MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  9. Asp.net MVC验证那些事(4)-- 自定义验证特性

    在项目的实际使用中,MVC默认提供的Validation Attribute往往不够用,难以应付现实中复杂多变的验证需求.比如, 在注册用户的过程中,往往需要用户勾选"免责声明", ...

最新文章

  1. linux+python+djiango+mysql编译安装学习笔记
  2. Console-算法-递归算法示例
  3. 一体化服务器和oracle集群,4种Oracle DBaaS部署模式,你在使用哪一种?
  4. Leetcode重点250题
  5. 计算机网络分层作业,计算机网络作业布置-参考答案
  6. 用for循环打印出九九乘法表
  7. json字符串转对象数组
  8. 利用GDAL根据栅格影像DN值实现颜色渲染
  9. ArcMap(ArcGIS)批量裁剪图片【超详细】
  10. smartUp手势插件Chrome
  11. 蓝字冲销是什么意思_什么叫红冲蓝补?
  12. js 删除节点小案例
  13. 分享一个自用小功能--微信小程序二维码签到
  14. notifier_call -----总结
  15. 【web-ctf】ctf_BUUCTF_web(2)
  16. torch.Tensor.requires_grad_(requires_grad=True)的使用说明
  17. 数字化门店管理|如何让门店数字化管理,更加贴合日常运营细节?
  18. 用python画一个汉字_python使用reportlab画图示例(含中文汉字)
  19. 饥荒更多食物制作mod食谱_您如何看待您附近的更好的食物?
  20. 吃货联盟订餐系统 java

热门文章

  1. java 写 gz_java简写名词解释 - osc_gzyujipq的个人空间 - OSCHINA - 中文开源技术交流社区...
  2. floquet端口必须沿z轴设置_Ansys Workbench 振动给料机偏心轴的模态分析
  3. 2018全国计算机音乐大赛一等奖,2018全国数字音乐大赛总决赛精彩无限!小学员的技能震惊评委!...
  4. 《零基础》MySQL GROUP BY 语句(十九)
  5. 2014 java面试题_2014 java面试题 (答案)
  6. android打包规范包含第三方库aar,Android Studio 打包AAR和第三方静态库(示例代码)
  7. 没有bug队——加贝——Python 练习实例 37,38
  8. matlab的fftn,matlab fftn
  9. 怎样在电脑上上传图片_电脑上回收站怎样恢复
  10. 飞行棋 c语言,骑士飞行棋【纯c】