Search Function ASP.NET MVC

Search Function In Each Column Using AJAX Table In ASP.NET MVC

Introduction

This article explains how to implement search functionality to each column as well as implement common search using AJAX table in ASP.NET MVC.

Background

We use tables or grids in our application but users expect  different functionalities in tables and grids. This article explains how to make search functionality for each field in tables. We can make common and separate field search functionality using AJAX table, jQuery and passing data as a JSON  format to the table. It is very helpful to users.

Steps For Create Ajax Table

Add a class in model  like below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxTable.Models
{
    public class Country
    {
        public int Rank { get; set; }
        public string CountryName { get; set; }
        public int pulation { get; set; }
    }
}
Add new controls and action methods and add action methods and method in controllers, like the below coding.
public class TableController : Controller
    {
        // GET: Table
        public ActionResult Index()
        {
            return View();
        }

        private List<Country> GetPopulation()
        {
            var populationList = new List<Country>
            {
                new Country
                {
                    Rank = 1,
                    CountryName = "Chine",
                    pulation = 1367485388
                },
                new Country
                {
                    Rank = 2,
                    CountryName = "India",
                    pulation = 1251695584
                },  
                new Country
                {
                    Rank = 3,
                    CountryName = "United State",
                    pulation = 321368864
                },
                new Country
                {
                    Rank = 4,
                    CountryName = "Indonesia",
                    pulation = 255993674
                },
                new Country
                {
                    Rank = 5,
                    CountryName = "Brazil",
                    pulation = 204259812
                },
                new Country
                {
                    Rank = 6,
                    CountryName = "Pakistan",
                    pulation = 199085847
                },
                new Country
                {
                    Rank = 7,
                    CountryName = "Nigeria",
                    pulation = 181562056
                },
                new Country
                {
                    Rank = 8,
                    CountryName = "Bangladesh",
                    pulation = 168957745
                },
                new Country
                {
                    Rank = 9,
                    CountryName = "Russia",
                    pulation = 142423773
                },
                new Country
                {
                    Rank = 10,
                    CountryName = "Japan",
                    pulation = 126919659
                }
            };

            return populationList;
        }
        public ActionResult getPopulation()
        {
            var population = GetPopulation();
            return Json(population);
        }
    }
Add view for corresponding action methods. After adding view we need to add three important CDNs in our view.

CDN for Table Styles
<link href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
CDN for jQuery
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
View Page Code
@{
    ViewBag.Title = "Index";
}
<link href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
<h2>Ajax Table Columns Search</h2>
<table id="tblPopulation">
    <thead>
        <tr>
            <td>Rank</td>
            <td>Country Name</td>
            <td>Population</td>
        </tr>
        <tr>
            <td>
                <input type="text" />
            </td>
            <td>
                <input type="text" />
            </td>
            <td>
                <input type="text"/>
            </td>
        </tr>
    </thead>
     
</table>
@section Scripts {
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({

            url: '/Table/getPopulation',
            dataType: "json",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: {},
            success: function (data) {
                var tr;
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    tr = tr + "<tr>";
                    tr = tr + "<td>" + data[i].Rank + "</td>";
                    tr = tr + "<td>" + data[i].CountryName + "</td>";
                    tr = tr + "<td>" + data[i].population + "</td>";
                    tr = tr + "</tr>";
                }
                $('#tblPopulation').append(tr);
                tblFormate();
            },
            error: function (xhr) {
                alert('No Valid Data');
            }
        });

        function tblFormate() {

            var table = $('#tblPopulation').DataTable(
             {
                 //"searching": false,
                 "lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]
             });
            //Apply the search
            table.columns().eq(0).each(function (colIdx) {
                $('input', table.column(colIdx).header()).on('keyup change', function () {
                    table
                        .column(colIdx)
                        .search(this.value)
                        .draw();
                });
            });
        }
       
    });
</script>

}
Explanation

We added table heading as well as added textbox for each column. We will be filtering data using corresponding text boxes. Using AJAX, we call the action methods from View to Controller and pass the data as a JSON from controller to view. JSON data will be appended to the tables.

We created one function for column search and normal table converted to an AJAX table with a default design.

Following function is very important to each column search.
function tblFormate() {

       // Convert normal table to Ajax table with default design
var table = $('#tblPopulation').DataTable(
             {
                 "lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]
             });
            //Each column seach based on columns
            table.columns().eq(0).each(function (colIdx) {
                $('input', table.column(colIdx).header()).on('keyup change', function () {
                    table
                        .column(colIdx)
                        .search(this.value)
                        .draw();
                });
            });
        }
Final Step

After adding the above-mentioned code just build and run the applications and we can see the output looks like the below screen shots.


After Column Search


Conclusion

I hope this article explains in a simple way, how to create each column search in ASP.Net MVC; and it helps many freshers and students.
Search Function ASP.NET MVC Search Function ASP.NET MVC Reviewed by Unknown on 10:16 AM Rating: 5

No comments:

agrsoft. Powered by Blogger.