Introducing Mvc.Jsonp

I’ve recently been doing some JSONP-related stuff with ASP.NET MVC 3, and I decided to make it into an open-source library. It provides a JsonpResult which is a subclass of MVC’s JsonResult, as well as an abstract JsonpControllerBase, from which you can subclass your controllers, which provides a Jsonp method (and various overloads) which return a JsonpResult.

So, let’s say you have a controller which you want to return JSONP. You could use the library like this:

public class StarshipController : JsonpControllerBase
{
    public JsonpResult Index(string callback = "myCallbackFunction")
    {
        var starships = new List<string>
        {
            "Enterprise", "Excalibur", "Yorktown", "Oberth", "Hood", "Reliant"
        };

        return this.Jsonp(starships, callback, JsonRequestBehavior.AllowGet);
    }
}

This will give you a response of application/javascript with this content:

myCallbackFunction(["Enterprise","Excalibur","Yorktown","Oberth","Hood","Reliant"]);

You can grab it at GitHub or get NuGet binaries.

blog comments powered by Disqus