项目需要,在使用KendoUI,又涉及到jsonp数据格式的处理,网上看到这样一种实现方法,在此小记一下(其实是因为公司里只能上博客园等少数网站,怕自己忘了,好查看一下,哈哈哈)

1. 新建控制器扩展类 ContollerExtensions.cs

public static class ContollerExtensions
{
  public static JsonpResult Jsonp(this Controller controller, object data)
  {
    JsonpResult result = new JsonpResult()
    {
      Data = data,
      JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
    return result;
  }

}

2.新建JsonpResult类,并继承JsonResult

public class JsonpResult : JsonResult
{
  private static readonly string JsonpCallbackName = "callback";
  private static readonly string CallbackApplicationType = "application/json";

  public override void ExecuteResult(ControllerContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException("context");
    }
    if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
    String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
    {
      throw new InvalidOperationException();
    }
    var response = context.HttpContext.Response;
    if (!String.IsNullOrEmpty(ContentType))
      response.ContentType = ContentType;
    else
      response.ContentType = CallbackApplicationType;
    if (ContentEncoding != null)
      response.ContentEncoding = this.ContentEncoding;
    if (Data != null)
    {
      String buffer;
      var request = context.HttpContext.Request;
      var serializer = new JavaScriptSerializer();
      if (request[JsonpCallbackName] != null)
        buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
      else
        buffer = serializer.Serialize(Data);
      response.Write(buffer);
    }
  }
}

3.在控制器中使用

public class ProductsController : Controller
{
  private static List<Product> products = new List<Product>()
  {
    new Product(){ProductID=10,ProductName="testPro1",UnitPrice=12,UnitsInStock=12,Discontinued=false},
    new Product(){ProductID=11,ProductName="testPro2",UnitPrice=1,UnitsInStock=12,Discontinued=false},
    new Product(){ProductID=12,ProductName="testPro3",UnitPrice=17,UnitsInStock=12,Discontinued=true},
    new Product(){ProductID=13,ProductName="testPro4",UnitPrice=22,UnitsInStock=12,Discontinued=false}
  };

  public ActionResult Index()
  {
    return View();
  }

  public JsonResult List()
  {
    return this.Jsonp(products);
  }
}

4.对应的视图,这里用了kendui的grid接收数据

@{
ViewBag.Title = "Grid Demo1";
}
<link href="~/Content/kendoui/examples-offline.css" rel="stylesheet" />
<link href="~/Content/kendoui/styles/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendoui/kendo.rtl.min.css" rel="stylesheet" />
<link href="~/Content/kendoui/styles/kendo.default.min.css" rel="stylesheet" />

<script src="~/Content/kendoui/js/jquery.min.js"></script>
<script src="~/Content/kendoui/js/kendo.view.min.js"></script>
<script src="~/Content/kendoui/console.js"></script>
<script src="~/Content/kendoui/js/kendo.all.min.js"></script>

<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
  dataSource: {
  type: "jsonp",
  transport: {
    read: "/Products/List"
  },
  pageSize: 20,
  schema: {
    model: {
    id: "ProductID",
    fields: {
      ProductID: { editable: false, nullable: true },
      ProductName: { validation: { required: true } },
      UnitPrice: { type: "number", validation: { required: true, min: 1 } },
      Discontinued: { type: "boolean" },
      UnitsInStock: { type: "number", validation: { min: 0, required: true } }
      }
    }
  }
  },
  height: 550,
  groupable: true,
  sortable: true,
  pageable: {
    refresh: true,
    pageSizes: true,
    buttonCount: 5
  },
  columns: [
    { field: "ProductName", title: "Product Name" },
    { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "100px" },
    { field: "UnitsInStock", title: "Units In Stock", width: "100px" },
    { field: "Discontinued", width: "100px" },
    { command: ["edit", "destroy"], title: "&nbsp;", width: "160px" }]
    });
  });
</script>
</div>

<style type="text/css">
.customer-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-left: 5px;
}

.customer-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
</style>

5.结果如下

Asp.net MVC 控制器扩展方法实现jsonp的更多相关文章

  1. ASP.NET MVC 控制器激活(一)

    ASP.NET MVC 控制器激活(一) 前言 在路由的篇章中讲解了路由的作用,讲着讲着就到了控制器部分了,从本篇开始来讲解MVC中的控制器,控制器是怎么来的?MVC框架对它做了什么?以及前面有的篇幅 ...

  2. Asp.Net MVC 控制器

    原文链接:http://www.asp.net/learn/mvc/ 这篇教程探索了ASP.NET MVC控制器(controller).控制器动作(controller action)和动作结果(a ...

  3. 详解ASP.NET MVC 控制器

    1   概述 在阅读本篇博文时,建议结合上篇博文:详解ASP.NET MVC 路由  一起阅读,效果可能会更好些. Controller(控制器)在ASP.NET MVC中负责控制所有客户端与服务端的 ...

  4. 【ASP.NET MVC系列】浅谈ASP.NET MVC 控制器

    ASP.NET MVC系列文章 [01]浅谈Google Chrome浏览器(理论篇) [02]浅谈Google Chrome浏览器(操作篇)(上) [03]浅谈Google Chrome浏览器(操作 ...

  5. ASP.NET MVC 控制器激活(二)

    ASP.NET MVC 控制器激活(二) 前言 在之前的篇幅中,用文字和图像来表示了控制器的激活过程,描述的角度都是从框架默认实现的角度去进行描述的,这样也使得大家都可以清楚的知道激活的过程以及其中涉 ...

  6. ASP.NET MVC 控制器激活(三)

    ASP.NET MVC 控制器激活(三) 前言 在上个篇幅中说到从控制器工厂的GetControllerInstance()方法来执行控制器的注入,本篇要讲是在GetControllerInstanc ...

  7. 学习ASP.NET MVC(二)——我的第一个ASP.NET MVC 控制器

    MVC全称是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范,用一种业务逻辑和数据显示分离的方法组织代码,将 ...

  8. MVC 用扩展方法执行自定义视图,替代 UIHint

    MVC 用扩展方法执行自定义视图,替代 UIHint 项目中用了 Bootstrap , 这样就不用写太多的CSS了,省去很多事情.但是这个业务系统需要输入的地方很多,每个表都有100多个字段,每个页 ...

  9. 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射

    使用Code First建模自引用关系笔记   原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...

随机推荐

  1. 三:vim常用快捷键

    窗口移动操作: j或者Ctrl+e(就是Ctrl+e):向下细微滚动窗口. k或者Ctrl+y:向上细微滚动窗口. h:向左细微滚动窗口. l:向右细微滚动窗口. gg:跳转到页面的顶部. G(就是s ...

  2. 自己写一个java的mvc框架吧(一)

    自己写一个mvc框架吧(一) 目录 自己写一个mvc框架吧(一) 自己写一个mvc框架吧(二) 自己写一个mvc框架吧(三) 自己写一个mvc框架吧(四) 写之前的一些废话 废话 1 (总是要先随便说 ...

  3. Sourcetree报错: 您没有已经配置扩展集成设置的远端

    一.错误提示 您没有已经配置扩展集成设置的远端; ... 二.解决 配置 Legacy Account Settings 即可:

  4. HashMap概述及其三种遍历方式

    一.HashMap概述: 1.HashMap是一个散列表,它存储的是键值对(key-value)映射: 2.HashMap继承AbstractMap,实现了Map,Cloneable,Serializ ...

  5. js中var、let、const区别

    javascript中有三种声明变量的方式:var.let.const 1.var 作用域:全局或局部 var的作用域可以是全局或是局部,以下分四种情况说明: (1).当var关键字声明于函数内时是局 ...

  6. marquee 滚动到文字上时停止滚动,自定义停止方法

    我要实现的效果如下图:当鼠标移到续费提醒文字上时,文字滚动停止,并出现后面的关闭按钮:当鼠标移出文字时,文字继续滚动,后面的关闭按钮不显示. 在网上查到的marquee停止滚动的的代码是这样的: &l ...

  7. thinkPHP3.2.2 控制器内跳转的三种方式

    public function jump() { $obj = new TestController(); $obj->logged(); } public function jump1() { ...

  8. 阿里云短信服务Java版

    短信服务管理平台 https://dysms.console.aliyun.com/dysms.htm java短信发送API    https://help.aliyun.com/document_ ...

  9. React-Native开发之原生模块封装(Android)升级版

     本文主题:如何实现原生代码的复用,即如何将原生模块封装. (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/52862 ...

  10. atitit。流程图的设计与制作 attilax 总结

    atitit.流程图的设计与制作 attilax 总结 1. 流程图的规范1 2. 绘图语言2 2.1. atitit.CSDN-markdown编辑器2 2.2. js-sequence-diagr ...