ASP.NET MVC中EasyUI的datagrid跨域调用实现代码

  最近项目中需要跨域调用其他项目的数据,其他项目也是使用的EasyUI的datagrid组件,开始以为直接在datagrid的url属性定义为其他项目的url地址即可,可是测试下发现的确是返回了json数据但是json数据提示“invalid label” 错误,网上搜索了下错误解决办法,参考 “JavaScript处理Json的invalid label错误解决办法“的方法利用datagrid的loadData方法加载并转换了json还是提示上述错误,感觉原因不在格式问题。

  搜索了下JavaScript跨域调用的文章“JavaScript跨域访问问题解决方法”得到启发,发现原来是因为easyUI使用的是JQuery的异步方法加载数据,应该遵循JQuery的跨域访问规则,也就是上述文章中提到的url中需要加入jsoncallback=?回调函数参数,并且返回的json的格式必须修改为:回调函数名(json数据),而现在返回的数据只是json格式的数据没有回调函数名,自然提示格式错误,于是修改了ASP.NET MVC自定义的JsonResult类,具体如何编写自定义的JsonResult类见:自定义ASP.NET MVC JsonResult序列化结果,

  代码如下:

  

复制代码 代码如下:

  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

  //跨域调用需要修改json格式jsoncallback

  if (context.HttpContext.Request.Params.AllKeys.Contains("jsoncallback"))

  {

  String callback = context.HttpContext.Request.Params["jsoncallback"];

  response.Write(callback+"("+JsonConvert.SerializeObject(Data)+")");

  }

  else

  {

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

  }

  #pragma warning restore 0618

  }

  }

  }

  EasyUI的datagrid的代码如下:

  

复制代码 代码如下:

  //datagrid

  $('#dg').datagrid({

  url:'http://localhost:9000/ManagementSystem/ListCurrent?department=sss&jsoncallback=?',

  pageNumber: 1,

  pageSize: 20,

  pageList: [20, 40, 60, 80, 100],

  onDblClickRow: function(rowIndex) {

  edit();

  }

  });

  作者:mikel

  出处:http://www.cnblogs.com/mikel/