[转]自定义ASP.NET MVC JsonResult序列化结果
本文转自: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组件中,解决这个问题其实有两种办法:
- 扩展EasyUI的datebox组件的parser函数自定义格式化日期格式,不过存在一个问题是如果使用form.load数据是先将值赋给datebox不会调用datebox的parser方法,只有在加载完form后再改变datebox的值为”2011-11-3”格式的值;
- 第二种方式就是本文要讲得修改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作为数据交换格式
- 扩展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);
}
}
[转]自定义ASP.NET MVC JsonResult序列化结果的更多相关文章
- vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板)
vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板): Customizing ASP.NET MVC 5/Web API 2 Scaffoldi ...
- 【记录】ASP.NET MVC JsonResult JsonRequestBehavior AllowGet
JS Ajax 调用代码: $.ajax({ url: "/AjaxController/GetInfoById", type: 'GET', datatype: "js ...
- Asp.NET MVC JSON序列化问题
最近在做项目的时候遇到一个JSON序列化问题. 环境:ASP.NET MVC 4.0 数据库:SQL 2008 在将获取的数据从后台以json的形式传给前台的easyui treegrid绑定的时候通 ...
- 转:自定义ASP.NET MVC Html辅助方法
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- 【MVC】自定义ASP.NET MVC Html辅助方法
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- [转载]自定义ASP.NET MVC Html辅助方法 TagBuilder
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- 创建可复用的自定义 ASP.NET MVC Helpers
通常,在ASP.NET MVC项目中App_Code目录下新建.cshtml编写类似下方的代码就能创建自定义的MVC Helper了, 假设文件名为StrHelper.cshtml,那么在别的视图中的 ...
- 自定义ASP.NET MVC Html辅助方法
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- 【草稿】自定义ASP.NET MVC Html辅助方法
https://www.cnblogs.com/myshell/archive/2010/05/09/1731269.html 在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其 ...
随机推荐
- 使用双引擎,让kbmmw 的客户端访问更方便(既给浏览器做服务,也给桌面程序做服务)
前面我们一直都讲了如何使用kbmmw smarthttpservice 给客户端提供REST 服务.主要都是返回给 浏览器访问的,如果我们使用delphi 开发桌面应用,如何使用这些服务呢?其实一切 ...
- 【POJ 1159】Palindrome
[POJ 1159]Palindrome 近期各种题各种奇葩思路已经司空见惯了...又新出个滚动数组= = 该题另一点须要知道 最少须要补充的字母数 = 原序列S的长度 - S和S'的最长公共子串长度 ...
- ajax访问json文件缓存问题
ajax访问json文件,json文件改动,访问的时候也不能及时看到改动后的内容. 这是因为浏览器缓存的原因. 在这时候就需要清除浏览器的缓存或者加上一个标记,让ajax访问文件的时候知道这是一个新的 ...
- NSString类的方法实现
创建一个新字符串并将其设置为 path 指定的文件的内容,使用字符编码enc,在error上返回错误 + (id)stringWithContentsOfURL:(NSURL *)url encodi ...
- Codeforces Round #346 (Div. 2) E. New Reform
E. New Reform time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- codeforces 690C2 C2. Brain Network (medium)(bfs+树的直径)
题目链接: C2. Brain Network (medium) time limit per test 2 seconds memory limit per test 256 megabytes i ...
- 如何使用BMap.Point传递变量、存储数据?
在开发中使用到了百度地图进行开发,用于展示企业位置.由于数据量庞大,如果使用marker,将会造成界面卡顿,处理慢的问题. 在查看百度地图API示例是发现了海量点这个东西,还别说对于大数量的点加载起来 ...
- fastText(二):微博短文本下fastText的应用(一)
众所周知,微博中的内容以短文本居多,文本内容随意性极强,这给建模增加了很大的难度.针对这一问题,这里分享一下fastText在微博短文本的应用. 任务目标简单介绍一下整个任务的目标:给微博内容打上标签 ...
- 【前端】Element-UI 省市县级联选择器 JSON数据
转载请注明出处:http://www.cnblogs.com/shamoyuu/p/element_cascader.html 不想自己处理的就直接下载吧 http://shamoyuu.bj.bce ...
- ul下的li浮动,如何是ul有li的高度
此时ul展示的界面为: ①给ul加上一个样式,display:inline-block; <html> <head> <title>float</title& ...