Skip to main content

Calling or consuming the ASP.Net Web API using jQuery and JavaScript

In our last post we have created our first Web API and invoked the web API directly from the browser; in this article we will use jQuery/JavaScript for calling the Web API methods.

So our Web API is already in setup and we’ll use same Web API methods (note that fixed list of Customer is updated only).

Replace the code of Index.cshtml view with the following:

<header>
    <div class="content-wrapper">
        <div class="float-left">
            <p class="site-title">
                <a href="~/">ASP.NET Web API</a>
            </p>
        </div>
    </div>
</header>
<div id="body">
    <section class="content-wrapper main-content clear-fix">
        <div>
            <h2>Search Customer by Id</h2>
            <input type="text" id="customerId" size="5" />
            <input id="filterButton" type="button" value="Search" />
        </div>
        <div>
            <h2>Customer list</h2>
            <table id="customer-list">
            </table>
        </div>
    </section>
</div>

@section scripts {
    <script>
        //Define api URL
        var apiUrl = 'api/customer';

        $(document).ready(function() {
            // load all customers on ready method.
            loadCustomers();

            //Filter button event
            $('#filterButton').click(function(event) {
                event.preventDefault();
                customerById();
            });
        });

        function loadCustomers() {
            // AJAX request
            $.getJSON(apiUrl)
                .done(function(data) {
                    //add header.
                    $('#customer-list').append(addHeader());

                    // On success, 'data' contains a list of customers.
                    $.each(data, function(key, item) {
                        // format item and add to tbody.
                        $('#customer-list').append(formatItem(item));
                    });
                });
        }

        function formatItem(item) {
            return '<tr><td>' + item.Id 
                + '</td><td>' + item.Name + '</td><td>'
                + item.Email + '</td><td>' + item.City 
                + '</td></tr>';
        }

        function addHeader() {
            return "<tr><th>Id</th><th>Name</th><th>Email</th><th>City</th></tr>";
        }

        function customerById() {

            //get customer id from textbox.
            var id = $('#customerId').val();

            //clear the table items.
            $('#customer-list').empty();

            if (id != '') {
                // AJAX request
                $.getJSON(apiUrl + '/' + id)
                    .done(function(data) {
                        $('#customer-list').append(addHeader())
                        .append(formatItem(data));
                    })
                    .fail(function(jqXhr, textStatus, err) {
                        $('#customer-list').empty().text('Customer Not Found');
                    });
            } else {
                // load all customers
                loadCustomers();
            }
        }
    </script>
}

In above code we have defined our HTML and then used jQuery to show data by calling our Web API methods, let’s simplify to code for more understanding.

Getting a list of all Customers

To get a list of all customers, we’ll need to send an HTTP GET request to /api/customer.

With the help of the jQuery getJSON function we’ll send an AJAX request to the API method. And then we’ll use the callback function “done” if the request succeeds. In this callback function, we update the DOM with the list of customers.

function loadCustomers() {
    // AJAX request
    $.getJSON(apiUrl)
        .done(function(data) {
            $('#customer-list').append(addHeader());
            // On success, 'data' contains a list of customers.
            $.each(data, function(key, item) {
                // format item and add to tbody.
                $('#customer-list').append(formatItem(item));
            });
        });
}

And call this method on “$(document).ready()” method, we have also wired up the Filter button on the ready method.

$(document).ready(function() {

    // load all customers on ready method.
    loadCustomers();

    //Filter button event
    $('#filterButton').click(function(event) {
        event.preventDefault();
        customerById();
     });
});

Getting a Customer by Id

To get a customer by Id, we’ll need to send an HTTP GET request to /api/customer/id, where id is the customer Id. For this jQuery getJSON function is used and then we’ll implement the callback function “done” if the request succeeds, else callback method “fail” will be used to show a user-friendly message(you can also show the exact error on the browser if you want).

function customerById() {

    //get customer id from textbox.
    var id = $('#customerId').val();
    //clear the table items.
    $('#customer-list').empty();
    if (id != '') {

        // AJAX request
        $.getJSON(apiUrl + '/' + id)
            .done(function(data) {
                $('#customer-list').append(addHeader())
                .append(formatItem(data));
            })
            .fail(function(jqXhr, textStatus, err) {
                $('#customer-list').empty().text('Customer Not Found');
            });
    } else {

        // load all customers
        loadCustomers();
    }
}

Other than this we have created two other functions in our jQuery code “addHeader” (to add table header) and “formatItem” (to format the JSON output in HTML for DOM)

Check the Output

Run the application to view the output of work:

By default all customers are shown.



You can filter customer by Id as:


If user enters wrong Id then it’ll show message “Customer Not Found”


You can also download a working sample of this post.

That’s it from now, hope you have enjoyed learning this, your comments and suggestions are most welcome J

Comments

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API , now let’s do some comparison of Web API with WCF and web services. Web Service WCF Web API Web services are created as files with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and the class name must end with “Controller”. It is SOAP based service and returns data in XML form. It is also based on SOAP and returns data in XML form. Web API is HTTP based service and by default, it returns data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted within the application or on IIS or using window service. It can be hosted within the application or on IIS. It is no...