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?