• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Wednesday, April 22, 2020

Consuming ASP.NET Web API Service From jQuery

 Admin     April 22, 2020     .Net, Web API     No comments   

In this article, I am going to discuss how to Consuming ASP.NET Web API Service From jQuery. We are going to work with the same example that we created in our previous article where we discussed Parameter Binding in ASP.NET WEB API. So please read our previous article before proceeding with this article.

Business Requirements:
When we click on the “Get All Employees” button, then we need to retrieve all the employee’s information and then display this information in an unordered list as shown in the image below. When we click on the “Clear” button then we need to clear the employees from the unordered list.
Consuming ASP.NET Web API Service From jQuery

Let’s discuss how to consuming ASP.NET Web API Service From jQuery
Modify the Employee Controller of our project as shown below where we create one action which will return the list of employees.
namespace WEB_API_Using_AJAX.Controllers
{
    public class EmployeeController : ApiController
    {
        [HttpGet]
        public IEnumerable<employee> GetEmployees()
        {
            EmployeeDBContext dbContext = new EmployeeDBContext();
            return dbContext.Employees.ToList();
        }
    }
}

Then modify the WebApiConfig class which is present in the inside App_Start folder as shown below. Here we are changing the URI pattern to allow action name as part of the URL.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Let’s add one Html Page to our project with the name HtmlPage1.html
Right-click on the project and then select Add => Html page as shown below
Consuming WEB API Service From jQuery - Adding HTML Page

In the next pop up specify the name for the HTML page and then click on the Ok button as shown in the image below
Consuming WEB API Service From jQuery - Providing Page Name

Once you created the page then copy and paste the following code in it.
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
            $('#btnGetEmployees').click(function () {
                $.ajax({
                    type: 'GET',
                    url: "api/Employees/GetEmployees",
                    dataType: 'json',
                    success: function (data) {
                        ulEmployees.empty();
                        $.each(data, function (index, val) {
                            ulEmployees.append('<li> First Name - ' + val.FirstName + " Last Name - " + val.LastName + " Gender- " + val.Gender + '</li>');
                        });
                    }
                });
            });
            $('#btnClear').click(function () {
                ulEmployees.empty();
            });
        });
    </script>
</head>
<body>
    <div>
        <input id="btnGetEmployees" type="button" value="Get All Employees" />
        <input id="btnClear" type="button" value="Clear" />
        <ul id="ulEmployees"></ul>
    </div>
</body>
</html>

That’s it, now run the application and navigate to the following URL in the browser

http://localhost:xxxxx/htmlpage1.html (instead of xxxxx you need to provide the port number where your application is running). It will display the following page.
Consuming WEB API Service From jQuery - HTML Page

Once you click on Get All Employees button it will display the employees data as unordered list as shown below on the below page.
How to Consuming ASP.NET Web API From jQuery

In this example, both the client (i.e. the HTML page that contains the AJAX code) and the ASP.NET Web API service are present in the same project so it worked without any problem. But, if they are present in different projects then this wouldn’t work.

Summary:
I Hope this post will be helpful to understand how to consume ASP.NET Web API Service using jQuery.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape