Fortunately there is a way around this. It’s called JSONP or “JSON with padding”. To summarize, JSONP works around the cross-domain browser restriction by making a GET request using a script tag, which isn’t limited by the same-origin policy. It traditionally will also provide a callback method in the url so the response from the server will look something like this:
- The first thing you need is the ability for your controller to return JSON or JSONP base on the request. As far as I know, there is not an out of the box JSONP Action Result in MVC, so we will create one.
The real meat of the class is where we write out the JSON result to the response object with it wrapped in the callback function:
response.Write(jsonp.Item2 + "(" + Data.ToJSON(useDataContract) + ")");
Important: The implementation of JSONP in jQuery is not without some flaws, one being it doesn’t raise errors when timeouts or error responses are given. Fortunately there is a plugin that handles that for you. I recommend looking at it if you get serious in consuming JSONP. http://code.google.com/p/jquery-jsonp/
Note: It the action result will default to just returning regular JSON if a callback parameter can’t be found in the request. This means you can use this instead of the JsonResult for even normal requests and they will automatically handle JSONP.
Codeplex is shutting down, I extracted the archive here.