Reputation: 893
I have a simple web service I wrote using Webmatrix that returns data in json. I liked to consume that service using ASP.NET MVC 3. I know how to do this with WCF but we are not going to use WCF on this project. Is there something akin to jquery's getJson() method in ASP.NET MVC where I just pass in the restful url and it returns the data and I handle it in a callback? Thanks for any help :-)
Here's my service:
URL:
/services/GetAllItemsService
Code:
@{
var items = ItemsService.GetAllItems();
Json.Write(items, Response.Output);
}
Upvotes: 3
Views: 2488
Reputation: 10344
JavaScriptSerializer
or Json.NETUpvotes: 0
Reputation: 1038710
You could use a WebClient to fetch the JSON data from a remote resource. For example:
using (var client = new WebClient())
{
string json = client.DownloadString("http://example.com/services/GetAllItemsService");
// TODO: do something with this JSON data, like for example deserialize into a model
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<SomeModel>(json);
}
Or if you wanted to write the JSON directly to the output:
using (var client = new WebClient())
{
string json = client.DownloadString("http://example.com/services/GetAllItemsService");
Response.Output.Write(json);
}
Upvotes: 4