I have a DataTable that is displaying all the records when the page is open. After that, when I select an item in my DropDownList, I need to filter the values. Filtering is working fine, but I have a problem refreshing the DataTable. I am returning the right JSON, but I don't know how to display it and refresh the DataTable. When I click on my button, it does the get method and returns the JSON, that I need to put in the DataTable. How can I do that?
This is my controller code:
public ActionResult GetData(int? izabranaZgrada)
{
ViewData["lista"] = GetAllZgrade();
if (izabranaZgrada == null || izabranaZgrada == 0)
// return View(GetAllKorisnik());
return Json(new { data = GetAllKorisnik() }, JsonRequestBehavior.AllowGet);
else
return Json(new { data = GetAllKorisnik().Where(zgr => zgr.id_zgrade == izabranaZgrada) }, JsonRequestBehavior.AllowGet);
}
This is my View:
<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
@using (Html.BeginForm("GetData", "Korisnik", FormMethod.Get))
{
<table>
<tr>
<td>
@Html.DropDownList("izabranaZgrada", new SelectList((System.Collections.IEnumerable)ViewData["lista"], "id", "naziv"), "Izaberite zgradu", htmlAttributes: new { @class = "form-control" })
</td>
<td><input type="submit" value="Pretraga" /></td>
</tr>
</table>
}
</p>
<table class="table table-striped table-condensed" id="tableKorisnik">
<thead>
<tr>
<th>
Ime i prezime
</th>
<th>
JMBG
</th>
<th>
Broj stana
</th>
<th>
Kvadratura
</th>
<th></th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
@section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#tableKorisnik").DataTable({
"ajax": {
"url": "/Korisnik/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "imePrezime" },
{ "data": "jmbg" },
{ "data": "brStana" },
{ "data": "kvadratura" },
{"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm 'style='margin-left:5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>"
},
"orderable": false,
"searchable": false,
"width": "150px"
}],
"language": {
"emptyTable": "No data. <b>Add new</b>"
}
});
});
</script>
}