I am developing a project using .Net core(MVC). I am trying to send data to populate a Datatable. My code inside the controller is like
public JsonResult Get_list(long? subject_id)
{
DataTable dt = ExamDA.GetTestBySubjectId((long)subject_id, GetString());
TestInfo test = JsonConvert.DeserializeObject<TestInfo>(json);
foreach (DataRow dr in dt.Rows)
{
test.Data.Add(new TestData()
{
Id = Convert.ToInt32(dr["Id"]),
Name = dr["Name"].ToString(),
DifficultyLevel = dr["DifficultyLevel"].ToString(),
CorrectMarks = Convert.ToDecimal(dr["CorrectMarks"]),
WrongMarks = Convert.ToDecimal(dr["WrongMarks"]),
strStartDate = dr["StartDate"].ToString(),
strEndDate = dr["EndDate"].ToString(),
});
}
//ViewBag.Columns = ti;
//return Json(test, new Newtonsoft.Json.JsonSerializerSettings());
return Json(test);
}
The code for Datatable in Columns section is like:
"columns": [
{ "data": "test", name: 'test', orderable: false, searchable: false }
]
But it is returning empty rows. Perhaps there is some problem with serialization. I have changed the code like:
columns: [
{ "data": Id },
{ "data": Name },
{ "data": DifficultyLevel },
{ "data": CorrectMarks },
{ "data": WrongMarks },
]
But no row is showing.
This code is add in controller
[HttpGet]
public IActionResult GetAll()
{
List<Company> objCompanyList = _unitOfWork.Company.GetAll().ToList();
return Json(new { data = objCompanyList });
}
create js file in www.root
var dataTable;
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": { url:'/admin/company/getall'},
"columns": [
{ "data": "name", "width": "15%" },
{ "data": "streetAddress", "width": "15%" },
{ "data": "city", "width": "15%" },
{ "data": "state", "width": "15%" },
{ "data": "phoneNumber", "width": "15%" },
{
data: 'id',
"render": function (data) {
return `<div class="w-75 btn-group" role="group">
<a href="/admin/company/upsert?id=${data}" class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
<a onClick=Delete('/admin/company/delete/${data}') class="btn btn-danger mx-2"> <i class="bi bi-trash-fill"></i> Delete</a>
</div>`
},
"width": "25%"
}
]
});
}
function Delete(url) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url,
type: 'DELETE',
success: function (data) {
dataTable.ajax.reload();
toastr.success(data.message);
}
})
}
})
}
this code add in view
<table id="tblData" class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Phone Number</th>
<th></th>
</tr>
</thead>
</table>
@section Scripts{
<script src="~/js/company.js"></script>
}