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

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...