How to operate WebAPI (display data) and webapi data
Just last year, Insus. NET wrote a WebAPI project and published it in IIS. See create and use Web API http://www.cnblogs.com/insus/p/5019088.html
You can view the instance from the above link.
Today, Insus. NET opens an ASP. net mvc project to operate on this Web API.
In the controller, create an Action:
Create a view as follows:
JQuery Ajax is used to obtain data, which is convenient and convenient. It is the jQuery code program marked with #3:
The url of the blue arrow in is the url path of the Web API.
Run the command to obtain the database results:
Normally, the demo has been completed so far, but Insus. NET idea, in ASP. the net mvc view does not want to use jQuery to display data. Instead, it wants to pass data into the view under control. When the view is complete, the data is displayed completely.
In a new project, create a model, which is the same as the Web API model:
Write a method for the HttpClient class to process the data returned by the Web API:
Public static IEnumerable <T> Get <T> (string url) {IEnumerable <T> model = null; var client = new HttpClient (); var task = client. getAsync (url ). continueWith (taskwithresponse) => {var response = taskwithresponse. result; var jsonString = response. content. readAsStringAsync (); jsonString. wait (); var json = jsonString. result. trimStart ('\"'). trimEnd ('\"'). replace ("\", ""); model = json. toObject <IEnumerable <T> () ;}); task. wait (); return model ;}Source Code
Create view operation:
Next, let's see how the view is written. There is no jQuery code at all:
The running effect is of course the same as that obtained by jQuery above !!!
If you only want to obtain a record, whether it is jQuery or HttpClient, you just need to modify the url of the API. To obtain a record with id 4, use the following url:
& Quot; http: // localhost: 9001/api/size/4 & quot"
For more information about the most basic Post, Put, and Delete functions of Web API operations, please follow up ....