1

My mvc page returns json by using the function Json(mycustomclass) to return a JsonResult object.

This works just fine except, I need to wrap the json in a callback so that jQuery can use it.

I want it like this:
jsonp1246168411282({"myjson":"some values"})

but I am getting this: {"myjson":"some values"}

Is there any way I can 'wrap' the C# JsonResult with brackets and the jquery callback?

Thanks

The Lorax

tereško
  • 58,060
  • 25
  • 98
  • 150
Simeon Wislang
  • 461
  • 2
  • 9
  • 21
  • For anyone else that needs a solution to this and doesn't want to use a WCF Service check this link out : http://stimms.blogspot.com/2009/04/aspnet-mvc-returning-jsonp.html – Simeon Wislang Jun 28 '09 at 09:59
  • or alternatively you can do this: string json_string = (callback + "(" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(json) + ")"); JavaScriptResult result = new JavaScriptResult(); result.Script = json_string; return result; – Simeon Wislang Jun 28 '09 at 10:20

2 Answers2

2

Jquery can use the json response just fine unless you are calling this action from a page in another domain. Is this what you are doing? If so I advise you to create a wcf service which supports jsonp. Example here

If not you can just use the getJson jquery method.

redsquare
  • 78,161
  • 20
  • 151
  • 159
  • Hi redsquare. Yes, my service needs to be accessible from other domains. Currently I have I view page that returns the json but I am working on a better solution that allows me to serialize a large custom class into json and return it as an object. I might just use an open source json serializer to turn it into a string and return it as a string. Thanks for your help thought. Best Regards, The Lorax – Simeon Wislang Jun 28 '09 at 09:28
0

ASP.net MVC returning JSONP

Also, something like:

public JavaScriptResult Test()
{
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    string callback = Request.Params["callback"] + "(" + javaScriptSerializer.Serialize("testing, testing") + ");";
    return JavaScript(callback);
}
Community
  • 1
  • 1
Hawkeye Parker
  • 7,817
  • 7
  • 44
  • 47