主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP
原文地址
http://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm
1.创建JsonpController
public class JsonpController : Controller { // GET: /Jsonp/ VoteUserRepository userrepository = new VoteUserRepository(); [HttpGet] public JsonpResult GetData(int? page) { var list = userrepository.GetModelList().Where(d => d.PhotoWorkInPoll != null).Where(d => d.PhotoWork.FirstOrDefault().State == 1); var userlist = from c in userrepository.GetPageModelList(list, 8, page ?? 1) select new { c.VoteUserID, c.UserName }; JsonpResult result = new JsonpResult(userlist); return result; } }
2.创建JsonpResult
public class JsonpResult : JsonResult { object data = null; public JsonpResult() { } public JsonpResult(object data) { this.data = data; } public override void ExecuteResult(ControllerContext controllerContext) { if (controllerContext != null) { HttpResponseBase Response = controllerContext.HttpContext.Response; HttpRequestBase Request = controllerContext.HttpContext.Request; string callbackfunction = Request["callback"]; if (string.IsNullOrEmpty(callbackfunction)) { throw new Exception("Callback function name must be provided in the request!"); } Response.ContentType = "application/x-javascript"; if (data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(data))); } } } }
Json数据内容地址:http://localhost:12111/Jsonp/GetData?page=1&callback=JsonCallback
格式例如如下:
JsonCallback([{"VoteUserID":1264,"UserName":"sjc196576 "},{"VoteUserID":1265,"UserName":"竹山县朱本双 "},{"VoteUserID":1266,"UserName":"qwe1725060988 "},{"VoteUserID":1267,"UserName":"堵河1982610 "},{"VoteUserID":1268,"UserName":"625297524 "},{"VoteUserID":1269,"UserName":"chen223150 "},{"VoteUserID":1270,"UserName":"1296909213 "},{"VoteUserID":1271,"UserName":"878223109 "}]);
3.其他页面调用数据方法
function TestCallback () { $.ajax({ type: "get", async: false, url: "http://localhost:12111/Jsonp/GetData?page=1&callback=JsonCallback", dataType: "jsonp", jsonp: "callback", jsonpCallback:"JsonCallback", success: function(json){ for (var i=0;i<7;i++){ alert(json[i].UserName); } }, error: function(){ alert('失败'); } }); }