Bind (Populate) CheckBoxList from database inside jQuery DataTable in ASP.Net Core MVC

Last Reply one month ago By dharmendr

Posted one month ago

bind checkboxlist from database in jquery datatable in asp.net core mvc

 

Posted one month ago

Hi rani,

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

Model

public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

Controller

public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult AjaxMethod()
    {
        List<Customer> customers = this.Context.Customers.ToList();
        List<SelectListItem> countries = this.Context.Customers.Select(x => new SelectListItem { Text = x.Country, Value = x.Country }).Distinct().Take(5).ToList();
        object[] data = new object[] { customers, countries };
        return Json(JsonConvert.SerializeObject(data));
    }
}

View

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        .dataTables_filter {
            display: none;
        }
    </style>
</head>
<body>
    <br />
    <div class="container">
        Name: <input type="text" id="txtSearch" />
        <table id="tblCustomers" class="table">
            <thead>
                <tr>
                    <th>Customer Id</th>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <script type="text/javascript">
        $(function () {
            var oTable;
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var datas = eval(response);
                    oTable = $("#tblCustomers").DataTable({
                        bLengthChange: true,
                        lengthMenu: [[2, 5, 10, -1], [2, 5, 10, "All"]],
                        bFilter: true,
                        bSort: true,
                        bPaginate: true,
                        data: datas[0],
                        columns: [
                            { 'data': 'CustomerID', 'searchable': false },
                            { 'data': 'ContactName' },
                            { 'data': 'City' },
                            {
                                'data': 'Country', 'searchable': false,
                                render: function (data, type, row, meta) {
                                    var country = data.toLowerCase();
                                    var countries = "";
                                    $.each(datas[1], function (i, item) {
                                        if (this.Text.toLowerCase() == country) {
                                            countries += "<input type='checkbox' checked /><span>" + this.Text + "</span></br>";
                                        } else {
                                            countries += "<input type='checkbox' /><span>" + this.Text + "</span></br>";
                                        }
                                    });
                                    return countries;
                                }
                            }
                        ],
                        fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                            if (aData.Country == "Mexico") {
                                $('td', nRow).css('background-color', '#D2D2D2');
                            } else {
                                $('td', nRow).css('background-color', 'Orange');
                            }
                        }
                    });
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

            $('#txtSearch').keyup(function () {
                oTable.search($(this).val()).draw();
            })
        });
    </script>
</body>
</html>

Screenshot