(Model Class) model class of Employee
public class Employee
{
public int Employee_id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public int Salary { get; set; }
}
Controller ActionResult it gets data from EmployeeGet
Class
public ActionResult Index()
{
EmployeeGet empgetObj = new EmployeeGet();
var getRecord = empgetObj.GetAllEmployees();
return Json(new{ data = getRecord}, JsonRequestBehavior.AllowGet);
}
Class to get record from database through query
public class EmployeeGet
{
string connString = (@"Data Source=DESKTOP-PK5A6U3\SQLEXPRESS;Initial Catalog = TableImplemented; Integrated Security = True");
public List<Employee> GetAllEmployees()
{
List<Employee> employees = new List<Employee>();
using (SqlConnection conn = new SqlConnection(connString))
{
var query = "select * from Employee";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Employee_id = Convert.ToInt32(rdr["Employee_id"]);
employee.Name = rdr["Name"].ToString();
employee.Contact = rdr["Contact"].ToString();
employee.Salary = Convert.ToInt32(rdr["Salary"]);
employees.Add(employee);
}
conn.Close();
}
}
return employees;
}
}
Index view In this view, I implement table
@{
ViewBag.Title = "Home Page";
}
<table id="tbleID" width="90%" class="display">
<thead>
<tr>
<th>Employee_id</th>
<th>Name</th>
<th>Contact</th>
<th>Salary</th>
</tr>
</thead>
</table>
This is my Ajax call for implementing dataTable
, but it is showing JSON type data not in DataTable form.
I used these two libraries to implement this Datatable:
//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" //cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
@section Scripts{
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
(function ($) {
debugger;
$("#tbleID").DataTable(
{
'ajax': {
'url': '/Home/Index',
'type': 'GET',
'contentType':"application/json; charset=utf-8",
'dataType': 'json',
},
'columns':
[
{ 'data': 'Employee_id', 'autoWidth': true },
{ 'data': 'Name', 'autoWidth': true },
{ 'data': 'Contact', 'autoWidth': true },
{ 'data': 'Salary', 'autoWidth': true }
]
});
});
</script>
}
jquery.js
in view? – hassan.ef/Home/Index
look like? – stuartd