Skip to main content

How to get/fetch data from ASP.Net WebAPI or how to query ASP.Net WebAPI.

In this article i am going to explain about How to get/fetch data from the WebAPI or how to query WebAPI.

In my previous article i have explained about How To Create Your First WEB API Project In ASP.Net MVC, Check Container Exists In Azure Blob Storage In C#.Net, Convert Dataset Datatable To Json Data Array In Asp.Net C#.Net & VB.Net Or How To Use JavaScriptSerializer To Convert Datatable To Json Data Array , How To Show Tooltip On Mouse Hover In Gridview In Using JQuery In ASP.Net C#.Net & VB.Net, SQL Script To Drop Multiple Tables,Procedures At Once , SQL Script To Drop Multiple Tables,Procedures At Once , Convert Dataset Datatable To Json Data Array, SQL Script To Drop Multiple Tables,Procedures At Once In Sql Server, and many articles in C#.Net,ASP.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.

Before proceeding to explain about how to get data from web api should know how to create the web api project. Read this article and then come to this article.

In the previous article i have created two controller methods. they are

Controller MethodURI
GetAllEmployees/api/employees
GetEmployee/api/employee/id

For the GetEmployee method, the id in the URI is a placeholder. For example, to get the employee with ID of 2, the URI is api/employee/2.

Now do the right click on the project select add then new item as shown in figure.

How to get fetch data from ASP.Net WebAPI or how to query ASP.Net WebAPI.

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html" like shown in below.

How to get fetch data from ASP.Net WebAPI or how to query ASP.Net WebAPI.

In the index.html i have included the jQuery library. And the file have two tables one for showing all the employees and another one is for showing particular employee details. The html file has a input field to input employee id and a button. While clicking on the button it will fetch the details for that particular employee id and display details in the table. Below is the entire code.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product App</title>
</head>
<body>

    <div>
        <h2>All Employees</h2>
        <table id="tblEmployees" border="1" style="border-collapse:collapse;"></table>
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="employeeId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
        <table id="tblEmployee" border="1" style="border-collapse:collapse;"></table>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
        var uri = 'api/employee';

        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    // On success, 'data' contains a list of products.
                    $('<tr>', { html: formHeader() }).appendTo($('#tblEmployees'));
                    $.each(data, function (key, item) {
                        // Add a row item for the product.
                        $('<tr>', { html: formatItem(item) }).appendTo($('#tblEmployees'));
                    });
                });
        });

        function formatItem(item) {
            return '<td>' + item.EmployeeId + '</td><td>' + item.EmployeeName + '</td><td>' + item.Department + '</td><td>' + item.Designation + '</td>';
        }
        function formHeader() {
            return '<th>EmployeeId </th><th>EmployeeName </th><th>Department </th><th>Designation</th>';
        }

        function find() {
            var id = $('#employeeId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#tblEmployee').html(formHeader());
                    $('<tr>', { html: formatItem(data) }).appendTo($('#tblEmployee'));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#tblEmployee').html('Error: ' + err);
                });
        }
    </script>
</body>
</html>


Now if you run the code you will get the below output.
Output of How to get fetch data from ASP.Net WebAPI or how to query ASP.Net WebAPI.

 Source code of How to get fetch data from the ASP.Net WebAPI or how to query ASP.Net WebAPI.

Hope you have enjoyed. Please share your comments and share this article.. Happy coding...

You May Also Like...


Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

CHECK IF FUNCTION EXISTS EXAMPLE

http://css-tricks.com/snippets/javascript/check-if-function-exists-before-calling/ When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn't exist. It makes sense on one page (the dependency is there) but not another. The difference is too slight to warrant forking the file into different versions. Instead, you can just check if the function exists before calling it to avoid the error: if ( typeof yourFunctionName == 'function' ) { yourFunctionName ( ) ; } jQuery code snippet to check whether a function exists within the JavaScript code. This can be easily achieved by using the jQuery.isFunction() function. Useful for checking if a jQuery function exists before calling it! < script type = "text/javascript" >      function  somenoobfunction ( )   {      }         // using jQuery      if   ( $. isFunction ( wi...