ASP.NET Tutorial: Call a Web API in.NET and use Bootstrap Filters to filter data with less code

WEB API is the ideal choice for developing resource-oriented services over HTTP/Restful, and it works well with MVC-based applications. WEB API is faster than WCF and may use any text format, including XML. I utilized the Bootstrap filter idea to filter the records of each column using a single textbox in this example. Bootstrap is used to create responsive web applications that work on all screen sizes. We may achieve this feature by utilizing Bootstrap CDN (for CSS and JS support).

Description
We can use a single textbox or search to filter records for each column in the database. We can create that feature to work on complex data with less code and in a matter of minutes. In this tutorial, I will demonstrate how to use Bootstrap.

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

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.

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.

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.

ASP.NET Core 8 Hosting Recommendation

HostForLIFE.eu

HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.