In this article, you will learn how to consume/use Web API in ASP.NET MVC step by step.
This article is the third part of my ASP.NET MVC Web API series.
Consuming Web API From jQuery
In this article, we have used localhost Web API and called for the GET request. The following is the process:
- Create ASP.NET MVC Project.
- Add an HTML file called Members.html file.
- Write GET call of for jQuery AJAX to fetch the data from ASP.NET Web API.
- System or process will throw two different errors.
- Resolve the errors with the solution given in this article.
- Run the project and check the output.
Step by Step Implementation
Create an new ASP.NET Empty Website project called “ConsumeWebApiFromJquery”.

By default, the Solution Explorer looks like this.

Now, right-click on the project titled “ConsumeWebApiFromJquery” and select ADD --> ADD NEW ITEM --> HTML Page. Give the page a name as “Members.html”.

Switch to Members.html file and add the following code.
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta charset="utf-8" />
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $.ajax({
- type: "GET",
- url: "http://localhost:52044/api/member",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- //Clear all previous list of members
- $("#MemberList").empty();
- //Display Asp.Net Web API response in console log
- //You can see console log value in developer tool
- //by pressing F12 function key.
- console.log(response);
- // Variable created to store <li>Memeber Detail</li>
- var ListValue = "";
- //Variable created to iterate the json array values.
- var i;
- //Generic loop to iterate the response arrays.
- for (i = 0; i < response.length; ++i) {
- ListValue += "<li>" + response[i].MemberName + " --- " + response[i].PhoneNumber
- }
- //Add/Append the formatted values of ListValue variable into ID called "MemberList"
- $("#MemberList").append(ListValue);
- },
- failure: function (response) {
- alert(response.responseText);
- alert("Failure");
- },
- error: function (response) {
- alert(response);
- alert("Error");
- }
- });
- });
- </script>
- </head>
- <body>
- <h2>C-Sharpcorner Member List</h2>
- <!--Member List will appened here -->
- <ul id="MemberList">
- </ul>
- </body>
- </html>




Hadshana KamalanathanPosted Aug 26, 2018, 11:15 AM
Nice article
Jignesh KumarPosted Aug 26, 2018, 8:47 AM
Nice article thank you for sharing series
Abhishek MishraPosted Aug 25, 2018, 1:41 PM
Really loved this series