In Part 1, Part 2, Part 3, and Part 4 of this series, we discussed HTTP Verbs and their implementation and custom method names. Now let’s discuss how to call Web API using jQuery Ajax.
Now in this, we will be designing a simple HTML page which will have a button and will display a list of values by calling web API Get() using jQuery Ajax call creating web API project as shown.
File - New Project - Select Asp.Net Web Application and add the name of the project, as shown below,
Now, select Web API, as shown below.
Now go to ValueController,
- public class ValuesController : ApiController
- {
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- public string Get(int id)
- {
- return "value";
- }
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- public void Delete(int id)
- {
- }
- }
Now, Add HTML page by right clicking - add - HtmlPage
Now, add the below code in HtmlPage1.html,
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <script src="Scripts/jquery-1.10.2.js"></script>
- <script type="text/javascript">
-
- $(document).ready(function () {
- var ulList = $('#ulList');
-
- $('#btn').click(function () {
- $.ajax({
- type: 'GET',
- url: 'http://localhost:15414/api/Values',
- dataType: 'json',
- success: function (data) {
-
- ulList.empty();
- $.each(data, function (index, val) {
- var fullName = val + ' ' + val;
- ulList.append('<li>' + fullName + '</li>')
-
- });
- }
-
- });
-
- });
-
-
- });
-
- </script>
-
- </head>
- <body>
- <input type="button" id="btn" value="Get List" />
- <ul id="ulList"></ul>
- </body>
- </html>
Now, in the above code we need to add a reference of jQuery libraries.
- <script src="Scripts/jquery-1.10.2.js"></script>
Now, we are calling click event of btn on document.ready
- $('#btn').click(function () {}
Now, on button click we are calling Web API Get() by providing URL as 'http://localhost:portno/api/Values' and specifying its type as Get. And onSuccess we are binding data to ulList.
Now, build and run the application and access HtmlPage1.html
Now, click on Get List button and you will get a list of values as shown in the below example.
In the next article, we will be discussing CORS; i.e. Cross-origin resource sharing in Web API.