Created
February 29, 2012 21:06
-
-
Save nikmd23/1944346 to your computer and use it in GitHub Desktop.
ASP.NET Action Result for JSONP (JSON + Padding)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Text; | |
| using System.Web; | |
| using System.Web.Mvc; | |
| using System.Web.Script.Serialization; | |
| namespace NikCodes.ActionResults | |
| { | |
| public class JsonpResult : ActionResult | |
| { | |
| public string CallbackFunction { get; set; } | |
| public Encoding ContentEncoding { get; set; } | |
| public string ContentType { get; set; } | |
| public object Data { get; set; } | |
| public JsonpResult(object data):this(data, null){} | |
| public JsonpResult(object data, string callbackFunction) | |
| { | |
| Data = data; | |
| CallbackFunction = callbackFunction; | |
| } | |
| public override void ExecuteResult(ControllerContext context) | |
| { | |
| if (context == null) throw new ArgumentNullException("context"); | |
| HttpResponseBase response = context.HttpContext.Response; | |
| response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/x-javascript" : ContentType; | |
| if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; | |
| if (Data != null) | |
| { | |
| HttpRequestBase request = context.HttpContext.Request; | |
| var callback = CallbackFunction ?? request.Params["callback"] ?? "callback"; | |
| #pragma warning disable 0618 // JavaScriptSerializer is no longer obsolete | |
| var serializer = new JavaScriptSerializer(); | |
| response.Write(string.Format("{0}({1});", callback, serializer.Serialize(Data))); | |
| #pragma warning restore 0618 | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment