Column Wise search and filter in WebGrid using TextBox and DropDownList in ASP.Net MVC

zeeshanpas
 
on Oct 19, 2021 03:42 AM
770 Views

Sir Almost i got the solution from your site its working fine but the problem is if i don't select anything in the dropdown rather than showing all data its showing empty but if i select any value in dropdown its working fine and in curriculum dropdown its working only for one value not for other.

Above is my javascript code

<script type="text/javascript">
        $(function () {
            //Add Header Row with TextBoxes.
            var row = $("<TR />");
            $("#WebGrid TR").eq(0).find("TH").each(function (index) {
                if (index == 0 || index == 1 || index == 2 || index == 3)
                    row.append('<th><input type = "text" class="form-control" /></th>');

                if(index==4)
                    row.append('<th><select onchange="OnChange(' + index + ',this);" id="DrpGrd" class="form-control drp" ><option value="" >Select Grade</option></select></th>');
               

                //populate Grade
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("GetGrade","Signup", new{area="" })',
                    dataType: "json",
                    contentType: "application/json",
                    success: function (response) {
                        $.each(response, function (data, value) {
                                $('#DrpGrd').append($("<option></option>").val(value.Grade_ID).text(value.Grade));

                        })

                    }
                });
                if (index == 5)
                    row.append('<th><select onchange="OnChange(' + index + ',this);" id="Drpcrm" class="form-control drp" ><option value="" >Select Curriculum</option></select></th>');

                //populate Curriculum
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("GetCurriculum", "Signup", new{area="" })',
                    dataType: "json",
                    contentType: "application/json",
                    success: function (response) {
                        $.each(response, function (data, value) {
                            $('#Drpcrm').append($("<option></option>").val(value.STATE_STANDARD_ID).text(value.StateStandard));

                        })

                    }
                });
            });
            $("#WebGrid TR").eq(0).after(row);

            //Applying the QuickSearch Plugin to each TextBox.
            $("#WebGrid TR").eq(1).find("INPUT").each(function (i) {
                $(this).quicksearch("#WebGrid tr:not(:has(th))", {
                    'testQuery': function (query, txt, row) {
                        return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                    }
                });
            });
        });

    function OnChange(colIndex, ele) {
        var query = $(ele).find('option:selected').text().toLowerCase();
        $("#WebGrid tr:not(:has(th))").each(function (i) {
            if (query == "select" || ($(this).find("td:eq(" + colIndex + ")").text().toLowerCase().indexOf(query) == 0)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
</script>

Could you please help me this??

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 20, 2021 02:13 AM
on Oct 26, 2021 01:57 AM

Hi zeeshanpas,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.Take(10).ToList());
    }

    public JsonResult GetCountries()
    {
        var objStandard = PopulateCountries();
        return Json(objStandard);
    }

    public List<Country> PopulateCountries()
    {
        List<Country> objstandard = new List<Country>();
        using (NorthwindEntities db = new NorthwindEntities())
        {
            var li = (from c in db.Customers
                        where c.Country != null
                        select new Country
                        {
                            Id = c.Country.Trim(),
                            Name = c.Country.Trim()
                        }).Distinct().ToList();
            objstandard = li.OrderBy(x => x.Name.Trim().ToLower()).Select(x => x).ToList();
        }

        return objstandard;
    }

    public class Country
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public JsonResult GetCities()
    {
        var objStandard = PopulateCities();
        return Json(objStandard);
    }

    public List<City> PopulateCities()
    {
        List<City> objstandard = new List<City>();
        using (NorthwindEntities db = new NorthwindEntities())
        {
            var li = (from c in db.Customers
                        where c.City != null
                        select new City
                        {
                            Id = c.City.Trim(),
                            Name = c.City.Trim()
                        }).Distinct().ToList();
            objstandard = li.OrderBy(x => x.Name.Trim().ToLower()).Select(x => x).ToList();
        }

        return objstandard;
    }

    public class City
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

View

@model IEnumerable<Filter_WebGrid_DropDownList_jQuery.Customer>

@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: false, canSort: false);
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
                 webGrid.Column("CustomerID", "Customer Id"),
                 webGrid.Column("ContactName", "Customer Name"),
                 webGrid.Column("City", "City"),
                 webGrid.Column("Country", "Country")))

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="~/Scripts/quicksearch.js"></script>
    <script type="text/javascript">
        $(function () {
            var row = $("<TR />");
            $("#WebGrid TR").eq(0).find("TH").each(function (index) {
                if (index == 0 || index == 1) {
                    row.append('<th><input type="text" class="form-control" /></th>');
                }

                if (index == 2) {
                    row.append('<th><select onchange="OnChange(' + index + ',this);" id="ddlCities" class="form-control drp"><option value="">Select City</option></select></th>');
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("GetCities", "Home", new{area="" })',
                        dataType: "json",
                        contentType: "application/json",
                        success: function (response) {
                            $.each(response, function (data, value) {
                                $('#ddlCities').append($("<option></option>").val(value.Id).text(value.Name));
                            })
                        }
                    });
                }

                if (index == 3) {
                    row.append('<th><select onchange="OnChange(' + index + ',this);" id="ddlCountries" class="form-control drp"><option value="">Select Country</option></select></th>');
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("GetCountries", "Home", new{area="" })',
                        dataType: "json",
                        contentType: "application/json",
                        success: function (response) {
                            $.each(response, function (data, value) {
                                $('#ddlCountries').append($("<option></option>").val(value.Id).text(value.Name));
                            })
                        }
                    });
                }
            });

            $("#WebGrid TR").eq(0).after(row);

            $("#WebGrid TR").eq(1).find("INPUT").each(function (i) {
                $(this).quicksearch("#WebGrid tr:not(:has(th))", {
                    'testQuery': function (query, txt, row) {
                        return Replacern($(row).children(":eq(" + i + ")").text().trim().toLowerCase()).indexOf(Replacern(query[0].toLowerCase())) != -1;
                    }
                });
            });
        });

        function OnChange(colIndex, ele) {
            var query = Replacern($(ele).find('option:selected').text().trim().toLowerCase());
            var selectedValue = Replacern($(ele).find('option:selected').val().trim().toLowerCase());
            $("#WebGrid tr:not(:has(th))").each(function (i) {
                if (selectedValue == "" || (Replacern($(this).find("td:eq(" + colIndex + ")").text().trim().toLowerCase()).indexOf(query) == 0)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }

        function Replacern(text) {
            return text.replace(/[\r\n]/g, "");
        }
    </script>
</body>
</html>

Screenshot