sunnyk21 says:
it only takes print of frst row
This is because you have multiple tbody section while rendering the table.
sunnyk21 says:
@
foreach
(var item
in
Model)
{
<tbody>
You have declared tbody inside the loop.
So multiple tbody is generated.
move the tbody outside the foreach loop.
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class EmployeeModel
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
List<EmployeeModel> model = new List<EmployeeModel>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Add(new EmployeeModel
{
Id = Convert.ToInt32(sdr["EmployeeID"]),
Name = sdr["FirstName"].ToString() + " " + sdr["LastName"].ToString(),
City = sdr["City"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
return View(model);
}
}
View
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/buttons/1.6.1/css/buttons.dataTables.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.1/js/buttons.print.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#tblEmployees').DataTable({
dom: 'Bfrtip',
buttons: ['print']
});
});
</script>
<table id="tblEmployees">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<% foreach (var item in Model)
{ %>
<tr>
<td><%: item.Id %></td>
<td><%: item.Name %></td>
<td><%: item.City %></td>
<td><%: item.Country %></td>
</tr>
<% } %>
</tbody>
</table>