June 1 2011
Supporting JSON-P with MVC is easy. Just derive a class from ActionResult, like this:
public class JsonpResult : ActionResult
{
public string Callback { get; set; }
public string Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/json";
if (this.Callback != null)
{
context.HttpContext.Response.Write(string.Format("{0}({1})", this.Callback, this.Content));
}
else
{
context.HttpContext.Response.Write(this.Content);
}
}
}
Then, in your controller, do the following, assuming you are looking for a querystring called callback (the json-p) convention as a method parameter to your action, and assuming that you have a string of json to send back, return this:
if (callback != null)
return new JsonpResult { Content = json, Callback = callback};
Note that I'm not having MVC handle serialization of my objects to JSON. I'm doing that all myself using the JSON classes from Microsoft.Serialization.Json from this project: http://wcf.codeplex.com/