0

I am using jquery DataTable() method, and it's working fine on page load; but I want to change the data of table on dropdown index change. For this, I am using $.getJason() to get data from controller on dropdown index changing.

Here is my Dropdown :

    @{
    List<SelectListItem> Countries = new List<SelectListItem>();
    foreach (System.Data.DataRow obj in (ViewData["countries"] as System.Data.DataTable).Rows)
    {
Countries.Add(new SelectListItem { Text = obj[1].ToString(), Value = obj[0].ToString() });
    }
}
     @Html.DropDownList("country", Countries, new { @class = "form-control" })

My table is :

<table id="cityList" class="table table-hover nowrap">
<thead>
<tr>
<td>City</td>
<td>Action</td>
</tr>
</thead>
<tbody id="tblCityBody">
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>

My Jason Method is :

$(document).ready(function () {
        $("#country").change(function () {
            url = '@Url.Action("FetchCities", "Setup")';
            var id = $(this).val();
            $.getJSON(url, { countryId: id }, function (response) {
                $.each(response, function (index, item) {
                    var html = "<tr><td>" + item.city + "</td>";
                    html += "<td><a href=\"#\" onclick=\"Delete(" + item.Id + ")\"><i class=\"ui-tooltip fa fa-trash\" style=\"font-size: 22px;\"></i></a></td></tr>";
                    $("#cityList tr:last").after(html);
                });

            });

        });
    })

in this code I am using a delete button; that's why I have added <a></a> tag in the table

My Method to get Cities List To Table is :

public JsonResult FetchCities(int countryId)
        {
            FastTrekContext context = new FastTrekContext();
            List<FastTrek.Models.CityModel> cities = new List<Models.CityModel>();
            DatabaseDealer dbd = new DatabaseDealer();
            dbd.command = new SqlCommand("SELECT top 1000 [Id],[city],[country_id] FROM [dbo].[cities] where [country_id]=" + countryId, con);
            DataTable dt = dbd.selectDataCommand();
            foreach (DataRow dr in dt.Rows)
            {
                FastTrek.Models.CityModel c = new FastTrek.Models.CityModel();
                c.Id = Convert.ToInt64(dr["id"]);
                c.city = dr["city"].ToString();
                cities.Add(c);
            }
            return Json(cities, JsonRequestBehavior.AllowGet);
        }

Its all working fine.... But jquery DataTable functions are not working in the generated table (change page index of table, search textbox and page item size dropdown)

I have also changed the code to bind data to table to this :

$("#country").change(function () {
            url = '@Url.Action("FetchCities", "Setup")';
            var id = $(this).val();
            $.getJSON(url, { countryId: id }, function (response) {
                $.each(response, function (index, item) {
                    var html = "<tr><td>" + item.city + "</td>";
                    html += "<td><a href=\"#\" onclick=\"Delete(" + item.Id + ")\"><i class=\"ui-tooltip fa fa-trash\" style=\"font-size: 22px;\"></i></a></td></tr>";
                    $("#cityList tr:last").after(html);
                });
                $('#cityList').DataTable({
                    responsive: true
                });
            });

        });

but it always returns error on every time I change the index of country dropdown.

My question is, Is there any method to bind <table><table> dynamically in jquery if we have json datatype?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • What is the error? –  Oct 08 '16 at 12:00
  • DataTables warning: table id=cityList - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3 –  Oct 08 '16 at 12:03
  • You need to edit that into your question. And did you try `destroy()` as per the link?. But [this answer](http://stackoverflow.com/questions/25929347/how-to-redraw-datatable-with-new-data) might help for adding rows if you do not want to destroy and reinitialize –  Oct 08 '16 at 12:06
  • i have used fnDestroy() but its not working –  Oct 08 '16 at 12:12
  • I cant see anything in your question about `fnDestroy()`! –  Oct 08 '16 at 12:14
  • My question is, Is there any method to bind dynamically in jquery if we have json datatype ? –  Oct 08 '16 at 12:22
  • Sure (refer an [example here](http://www.techstrikers.com/Articles/jquery-datatable-bind-json-using-asp.net-mvc5.php)), but if you want to **re-bind** it, you need to destroy and re-initialize –  Oct 08 '16 at 12:30
  • i am already using this method! it working fine on page load but when i use dropdown change index to get data, it also fills the table but table functionalities like table index change, table search textbox, table sorting......... not work. Can you give me an example of table destroy and recreate table with jquery bind –  Oct 08 '16 at 12:45
  • The documentation you linked to has an example (see the _destroy_ sub heading). Alernatively you can use the `row.add()` method inside your `$.each()` method to add the rows, in which case you do not need to destroy and reinitialize –  Oct 09 '16 at 03:27

0 Answers0