JSON-P and MVC

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/

Comments (1) -

6/3/2011 9:33:35 PM #

Auto Loan Vermont

Hey I pair your style I instrument concur for your take gratify remain transmitting!

Auto Loan Vermont

8/16/2011 2:37:58 PM #

Московские путаны

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.

Московские путаны

Pingbacks and trackbacks (1)+

Add comment

Enter your name, handle, alias, or email.

We'll incarnate your avatar from the services below.



biuquote
Loading