Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.net MVC returning JSONP
    primarykey
    data
    text
    <p>I am looking to return some JSON across domains and I understand that the way to do this is through JSONP rather than pure JSON. I am using ASP.net MVC so I was thinking about just extending the JSONResult type and then extendig Controller so that it also implemented a Jsonp method. Is this the best way to go about it or is there a built in ActionResult which might be better?</p> <p>Edit: I went ahead and did that. Just for reference sake I added a new result:</p> <pre><code>public class JsonpResult : System.Web.Mvc.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/javascript"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { // The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1 #pragma warning disable 0618 HttpRequestBase request = context.HttpContext.Request; JavaScriptSerializer serializer = new JavaScriptSerializer(); response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")"); #pragma warning restore 0618 } } } </code></pre> <p>and also a couple of methods to a superclass of all my controllers:</p> <pre><code>protected internal JsonpResult Jsonp(object data) { return Jsonp(data, null /* contentType */); } protected internal JsonpResult Jsonp(object data, string contentType) { return Jsonp(data, contentType, null); } protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding) { return new JsonpResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding }; } </code></pre> <p>Works like a charm. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload