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

本文转自:http://blog.163.com/[email protected]/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);

}

}

时间: 2024-08-25 22:30:42

[转]自定义ASP.NET MVC JsonResult序列化结果的相关文章

【MVC】自定义ASP.NET MVC Html辅助方法

在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么,我们就可以通过自己定义一个Html扩展方法来达到这个目的. 比如,到目前为止,Html扩展方法中没有关于<input type="file" />这类标签的辅助方法,那么我们就可以自已实现一个.本文以实现<input type="file" />

Asp.NET MVC JSON序列化问题

最近在做项目的时候遇到一个JSON序列化问题. 环境:ASP.NET MVC 4.0 数据库:SQL 2008 在将获取的数据从后台以json的形式传给前台的easyui treegrid绑定的时候通过追踪提示:使用JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength属性. 数据查询的表字段比较多,查出来的数据4000多行,在网上搜的资料普遍都是如下: <system.web.extensions> <scrip

Asp.net MVC JsonResult 忽略属性

指定 JavaScriptSerializer 不序列化公共属性或公共字段.无法继承此类. 命名空间:  System.Web.Script.Serialization 程序集:  System.Web.Extensions(在 System.Web.Extensions.dll 中) public class Person  {         public int ID { get; set; } public string Name { get; set; } public int Age

[转]Asp.NET MVC Widget开发 - ViewEngine

本文转自:http://www.cnblogs.com/hsinlu/archive/2011/03/02/1968796.html 在Asp.NET开发博客类系统,我们经常都会用到Widget,像在线好友.最近访问好友.最新留言等,关于Asp.NET MVC与Asp.NET视图的差异,这里不再说了,大家可去查一下,接下来我以“我的好友”列表来要介绍在Asp.NET MVC实现这一功能以及结构设计. 开发工具:VS 2010 EN 开发语言:Visual C# ASP.NET MVC 3 Asp

ASP.NET MVC 学习

ASP.NET MVC 学习 一. 学习MVC基础 MVC的三个字母分别代表什么意思? M—Model(模型).V—View(视图).C—Controller(控制器) VS2010 中建立MVC应用程序会自动生成哪些文件夹? Controllers – 放置Controller 类,处理URL 请求. Models – 放置业务实体类,表示和操作数据. Views – 放置UI 模板文件,负责展示输出结果. Scripts – 放置Javascript 类库文件和.js 文件. Content

学习ASP.NET MVC5框架揭秘笔记-ASP.NET MVC是如何运行的(三)

Controller的激活 ASP.NET MVC的路由系统通过注册的路由表对当前HTTP请求实施路由解析,从而得到一个用于封装路由数据的RouteData对象,这个过程是通过自定义的UrlRoutingModule对HttpApplication的PostResolveRequestCache事件进行注册实现的.由于得到的RouteData对象中已经包含了目标Controller的名称,我们需要根据该名称激活对应的Controller对象. 1.MvcRouteHandler 通过前面的介绍我

ASP.NET MVC学习目录

一.ASP.NET MVC原理详解 1.了解MVC架构模式 3.学习ASP.NET MVC的必备语言知识 4.MVC中的razor语法详解 5.ASP.NET MVC路由系统机制详细讲解 6.ASP.NET MVC输出生成Url链接详解 7.自定义ASP.NET MVC路由系统截获MVC的路由请求 8.ASP.NET MVC使用Area区域,使用功能模块清晰明了 9.ASP.NET MVC的Controller介绍 10.ASP.NET MVC的Controller接收输入详解 11.ASP.N

ASP.NET MVC AJAX调用JsonResult方法并返回自定义错误信息

一.如何用AJAX调用JsonResult方法 比如FuckController中添加有个返回JsonResult类型的方法FuckJson(): public JsonResult FuckJson() { return new JsonResult() { Data = new List<string>() { "fuck", "shit" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }

asp.net mvc自定义JsonResult类来防止MaxJsonLength超过限制

前不久在做一个项目的时候,我用到了mvc的webapi返回了一个大数据,结果报了500错误,如下图所示: Server Error in ‘/’ Application. Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Des