Using JSON data in ASP.NET MVC - asp.net-mvc

I have not done this before, so need some leads. I have a ASP.NET MVC4 (beta) project - Mobile project - setup. And I am given a set of REST APIs to consume. How would I do this? The APIs return data in JSON format. Do you have any examples, best practices...?

You could use the $.ajax method to send an AJAX request to the Web Api controller on the server:
$.ajax({
url: 'api/values/123',
type: 'GET',
success: function(data) {
// if the controller returned JSON data, the data argument
// will represent a javascript object that you could directly
// access its properties
}
});

Use DownloadString method of WebClient class. That will give you a string output of what the RESTURL is returning. You can convert that to Json and iterate the results
string address="http://yourrestdomain/customer/234";
WebClient client = new WebClient ();
string reply = client.DownloadString (address);

Related

How to call a service url for POST while passing body parameter in asp.net mvc controller?

I am new to asp.net mvc
I have a service url, I have tested it in postman..it is showing me the result.
But I am unable to understand, how can I pass the Body parameter programatically in the controller while calling the service.
I have tried like this:
string reqData = "{ \"Text\":\""+text+"\""+ ",\"UserID\" : \"10098\",\"EventID\":\"42\"}";
Please help, as I am very new to this.
You have to get data with http request in service.
getFunction(){
return this.http.get('URL')
.map(res => res.json());
}
And in the frontside,
this.'servicename'.getFunction().subscribe(x=>{
this.x = x;
});

Returning result for .net Web Api from db call

I'm new to the .net Web API and am trying to figure out how I return a Get result from a call to my database. I know everything works in my regular MVC page. But Not sure how to return the result from the Web API controller. I thought it was as simple as returning Json with the result. Here is my code:
// GET api/<controller>
public IEnumerable<string> Get()
{
using (var _db = new JobsDatabaseEntities())
{
var user = Env.CurrentUser;
var posts =
_db.JobPostings.Where(
j =>
j.City.Equals(user.City, StringComparison.OrdinalIgnoreCase) &&
j.Industry.ID == user.Industry.ID);
var result = new List<BusJobPost>();
foreach (var post in posts)
{
var p = new BusJobPost(post);
result.Add(p);
}
return Json(result);
}
}
Please visit this resource: Action Results in Web API 2. Your case is described in fourth section Some other type (which is applicable to first version of Web API as well).
In Web API you don't return JSON result explicitly. It is actually done by process called Content Negotiation. You can read about it here [Content Negotiation in ASP.NET Web API] in detail.
Highlighting briefly just some of this:
You can set Accept header for you request as: Accept: application/json (for example, if you use jquery ajax function: dataType: 'json')
Or even if you don't use Accept header at all, if you send request with JSON data, you should also get response back in JSON format
So you should just return result variable from your controller action and satisfy some of conditions to get response serialized into JSON.

jquery ajax call to ASP.NET MVC controller returns a MediaTypeFormatter exception

Technical Background - We're using :
1) asp.net 4.5 with VS2012
2) Durandal JS for building Single-Page-Apps (SPAs).
3) Breeze JS for querying data.
Now in my jquery ajax call, I'm calling into the Breeze Web API controller as follows:
jsonData.push({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds.data() // ds dataset is coming from a grid
});
var jsonDataStr = JSON.stringify(jsonData); CONVERT DATA TO JSON
var jq = $.ajax({
url: '/api/breeze/UpdateNode/',
type: "PUT",
dataType: "json",
data:jsonDataStr,
async: false,
});
and my controller looks like this:
[HttpPut]
public SaveResult UpdateNode(JObject saveBundle)
{
SaveResult saved = new SaveResult();
return saved;
}
However I'm getting the following exception return from my jQuery FAILED EVENT :
"ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'JObject' from content with media type 'application/x-www-form-urlencoded'.
So my main question is: how can I make a successful call into my Breeze API controller with the correct JSON data ?
UPDATE AT 1:50pm EST: If I specify type: "STRING" or "JSON" in my jquery ajax call, define my parameter type as STRING in my c# Controller method, the call works fine. However, ideally I want to pass this data object as JSON and my controller should handle it properly.
Thanks in advanced.
Bob
Your controller will need [BreezeController] attribute as mentioned here http://www.breezejs.com/documentation/web-api-controller
I had to change my javascript code to NOT use the javascript array and the subsequenst jsonData.push() and stringify().
Instead I needed a straight jsonData={} object as follows :
var jsonData = JSON.stringify({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds._data // gives me just the data from Kendo grid data source
});
I was then able to successfully make an ajax call to my controller as follows :
var jq = $.ajax({
url: '/api/breeze/UpdateNode',
type: "post",
dataType: "json",
contentType: 'application/json',
data: jsonData
});
All is good and I'm able to nicely put a break point inside my controller and receive the JObject parameter with issue.
thank you.
Bob

TypeScript with Angular.JS and web API

I'm working on an asp.mvc3 web api project. in this project I use TypeScript and Angular.js
and I need to access the business layer from TypeScript through the Web API. I called the Web API inside the constructor method in TypeScript using the
code given below.
constructor($scope, $http: any) {
$scope.VM = this;
$http.get("/API/PrivateAPI/Test/1").success((a) => { this.Tiles = a });
var bb = this.Tiles;
}
However, when trying to get the object list from the business layer, the Tiles array is empty. I debugged the code and found out the Web API is called after passing the last line of the constructor and does return results. I need to call that method inside the constructor and get object list to the Tiles array.
Does anyone know how to do so?
First of, I think you should do the following (notice .data) :
$http.get("/API/PrivateAPI/Test/1").success((response) => { this.Tiles = response.data });
Anyways, $http only supports async http requests. What you want can be done by a synchronous XHR request and that is considered bad UI experience, since the browser window freezes till the XHR request completes, and therefore $http doesn't support it (configuration docs).
What you can do is something like :
call another function from response e.g.
(response) => { this.Tiles = response.data; this.continueWithProcessing(); }
Or, Setup a variable to hide a preloader when the response comes back:
(response) => { this.Tiles = response.data; this.allDone=true; }
Where you have an ng-show on something like:
<div ng-show="!VM.allDone">Loading the data....</div>
Or both :)
Note: An async setting is supported in underlying browsers native XHR object and therefore in $.ajax which is the jquery ajax function : http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings. However it is a horrible UI experience + if you use it from angular you are responsible for scope.apply.

How to read json file format and how to write the json in c# asp.net

In my ASP.NET MVC project I am conecting to a remote cloud server which is returning the data in json like:
[{
"name":"new-service-dev",
"Isenabled":"true",
"ttl":86400,
"cdn_uri":"http://c0099.cdn2.files.rackspacecloud.com",
"referrer_acl":"",
"useragent_acl":"",
"log_":"false"
}]
Now I want to get all the values in list or array format, for example I want to get "cdn_uri".
I also want to create JSON somewhere in my code, how do I create and write JSON?
You can use the JSON.Net component from codeplex:
http://json.codeplex.com/
This will let you read/write JSON. Here's a simple example using your JSON from the question:
static void Main(string[] args)
{
JObject o =
JObject.Parse(
"{ \"name\":\"new-service-dev\", \"Isenabled\":\"true\", \"ttl\":86400, \"cdn_uri\":\"http://c0099.cdn2.files.rackspacecloud.com\", \"referrer_acl\":\"\", \"useragent_acl\":\"\", \"log_\":\"false\"}");
string cdn_uri = (string)o.SelectToken("cdn_uri");
Console.WriteLine(cdn_uri);
Console.ReadKey();
}
asp.net has an extension dll called system.web.extensions which is having support for javascript and json serialization. see this link

Resources