Skip to content

Instantly share code, notes, and snippets.

@nikmd23
Created February 29, 2012 21:06
Show Gist options
  • Select an option

  • Save nikmd23/1944346 to your computer and use it in GitHub Desktop.

Select an option

Save nikmd23/1944346 to your computer and use it in GitHub Desktop.
ASP.NET Action Result for JSONP (JSON + Padding)
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