Call Web API in .NET and Filter Data using Bootstrap Filters with Less Code

Introduction

WEB API is the best fit to create resource-oriented services using HTTP/Restful, and it works well with MVC-based applications. WEB API can use any text format, including XML, and is faster than WCF. Here I have used the Bootstrap filter concept to filter the records of each column using a single textbox. Bootstrap is used to make responsive web applications and supports all types of screen sizes. Using Bootstrap CDN (for CSS and JS support), we can achieve this feature.

Description

We can filter records for each columns in table with single textbox or search. With less code and few mins, We can implement that feature to work on complex data. In this article, I will show the steps for call Web API and filter records using Bootstrap.

  1. Call Web API using MVC controller
  2. Create view to support Bootstrap
  3. Filter records using Bootstrap Filters

Before going through this article, visit my previous articles as mentioned below.

Steps to be followed

Step 1

So, I already have discussed the steps to create Web API. You can visit Part 11 and Part 12 from the above index. Now, I will show the steps to call Web API in ASP.NET MVC application.

First I have created a Model class file named EmployeeViewModel.cs  and declare all entities which are same as Web API JSON response entities.

Code Ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCConsumeWebAPI.Models
{
    public class EmployeeViewModel
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public Nullable<int> Salary { get; set; }
    }
}

Code Description

Here all properties should be simillar to Web API response entities. So, when we call web api (whether internal or external API) that response we get should be simillar to your model properties.

Step 2

Then create a empty controller to call Web API named BootstrapFiltersController.

Code Ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using MVCConsumeWebAPI.Models;

namespace MVCConsumeWebAPI.Controllers
{
    public class BootstrapFiltersController : Controller
    {
        // GET: BootstrapFilters
        public ActionResult FilterEmployees()
        {
            IEnumerable<EmployeeViewModel> members = null;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:51259/api/");

                //Called Employee default GET All records  
                //GetAsync to send a GET request                  
                var responseTask = client.GetAsync("Employee");
                responseTask.Wait();

                //To store result of web api response.   
                var result = responseTask.Result;

                //If success received   
                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync<IList<EmployeeViewModel>>();
                    readTask.Wait();

                    members = readTask.Result;
                }
                else
                {
                    //Error response received   
                    members = Enumerable.Empty<EmployeeViewModel>();
                    ModelState.AddModelError(string.Empty, "Server error try after some time.");
                }
            }
            return View(members); //create a view result object by using model that renders a view
        }
    }
}

Code Description

Here I call the Web API as hown below.

client.BaseAddress = new Uri("http://localhost:51259/api/");

and the below line to send a GET request using GetAsync method and here Employee is the Web API controller.

Here the Web API response as shown below.

Web API response

var responseTask = client.GetAsync("Employee");

The remaining code is described with comment section.

Step 3

Here I created a Razor view named FilterEmployees.cshtml as empty template to avoid the use of _Layout.cshtml as shown below.

create a Razor view

Code Ref

@model IEnumerable<MVCConsumeWebAPI.Models.EmployeeViewModel>

@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Filter Employees</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
    <div class="container mt-3">
        <h2 class="text-primary">Bootstrap Filters <span class="badge badge-success">Filters Employees Details</span></h2>        
        <input class="form-control" id="myInput" type="text" placeholder="Search for First Name, Last Name, Gender and Salary..">
        <br>

        <table class="table table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.FirstName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.LastName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Gender)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Salary)
                    </th>
                </tr>
            </thead>
            <tbody id="myTable">
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.FirstName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.LastName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Gender)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Salary)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

</body>
</html>

Code Description

Use the CDN urls to support the CSS and JS remotely. We can imeplement Bootstrap table and Bootstrap filter.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

The bootstrap table that is used to contain the records with comes from Web API.

<table class="table table-bordered">
    <thead class="thead-dark">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Salary)
            </th>
        </tr>
    </thead>
    <tbody id="myTable">
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Gender)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Salary)
                </td>
            </tr>
        }
    </tbody>
</table>

Use jQuery to quick filter/search for table records. Here the ID of search textbox and tbody of Table are used.

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

Using jQuery to loop through each table rows to check if there are any text values that matches the value of the input field. There is a toggle method which hides the row (display:none) that does not match the search. By using the toLowerCase() method to convert the text to lower case.

Output

The interface is shown as below.

Filter Data using Bootstrap Filters

Filter using first names.

Filter Data using Bootstrap Filters

 

Filter using last names.

Filter Data using Bootstrap Filters

Filter using gender.

Filter Data using Bootstrap Filters

 

Filter using salary.

Filter Data using Bootstrap Filters

Check responsive web page using Bootstrap.

Filter Data using Bootstrap Filters

Summary

In this write-up, we have learned the below details,

  1. Call Web API using MVC controller
  2. Create view to support Bootstrap
  3. Filter records using Bootstrap Filters

Thank You & Stay Tuned For More


Similar Articles