ASP.NET MVC 3 JSONP: Does this work with JsonValueProviderFactory?

As far as receiving a JSON string and binding it to a model is concerned the JsonValueProviderFactory does this job out of the box in ASP.NET MVC 3. But there is nothing built-in for outputting JSONP. You could write a custom JsonpResult:

public class JsonpResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        var request = context.HttpContext.Request;
        var response = context.HttpContext.Response;
        string jsoncallback = (context.RouteData.Values["jsoncallback"] as string) ?? request["jsoncallback"];
        if (!string.IsNullOrEmpty(jsoncallback))
        {
            if (string.IsNullOrEmpty(base.ContentType))
            {
                base.ContentType = "application/x-javascript";
            }
            response.Write(string.Format("{0}(", jsoncallback));
        }
        base.ExecuteResult(context);
        if (!string.IsNullOrEmpty(jsoncallback))
        {
            response.Write(")");
        }
    }
}

And then in your controller action:

public ActionResult Foo()
{
    return new JsonpResult
    {
        Data = new { Prop1 = "value1", Prop2 = "value2" },
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
}

which could be consumed from another domain with $.getJSON():

$.getJSON('http://example.com/home/foo?jsoncallback=?', function(data) {
    alert(data.Prop1);
});

Leave a Comment