When we need a database table to display on our Webpage in MVC, basically we prefer model binding methodology. If our budget is high, we go for some third party tools like Kendo, Dev Express, Telerik etc., which costs us a lot and as a common developer or as a small start up company, it is very difficult to purchase such types of tools and ultimately we go for traditional techniques, which don't give us greater productivity.
Here, I am going to introduce to you a tool, which is completely free of cost, has faster fetching capacity, rich and modern functional features, good security, much less configuration and a smoothly behaving UI. I have been using it for my projects for many days and believe me, it's awesome.
It is DataTable
As I mentioned above, it needs much less configuration. I will complete this session with very few steps. I hope, you can understand it and start implementing it in your project from here on out.
Let's take a scenario, where we have a product information table and we want to show on our product list page.
Products
ProdID |
ProdName |
Manufacturer |
Price |
Stock |
Step 1 - Create a Product Model Class, as given below-
- public class Products {
- publicint ProdID {
- get;
- set;
- }
- publicstring ProdName {
- get;
- set;
- }
- publicstring Manufacturer {
- get;
- set;
- }
- publicdecimal Price {
- get;
- set;
- }
- publicint Stock {
- get;
- set;
- }
- }
Step 2 - Code to read from the database. You may write this method inside the controller or your separate DB handler class.
- public DataTable GetProducts() {
- string query = "SELECT ProdID,ProdName,Manufacturer,Price,Stock FROM Products ORDER BY ProdID DESC";
- SqlConnection connection = newSqlConnection();
- connection.ConnectionString = "your connection string";
- SqlCommand command = newSqlCommand(query, connection);
- SqlDataAdapter adapter = newSqlDataAdapter();
- adapter.SelectCommand = command;
- DataTable table = newDataTable();
- adapter.Fill(table);
- return table;
- }
Step 3 - Call GetProducts(), retrieve from the table and create a list object to contain product info. The method should return Json. This method must be written in controller.
- public JsonResult GetProductList() {
- List < Products > listProducts = newList < Products > ();
- DataTable table = GetProducts();
- foreach(DataRow row in table.Rows) {
- Products objProducts = newProducts();
- objProducts.ProdID = Convert.ToInt32(row["ProdID"]);
- objProducts.ProdName = row["ProdName"].ToString();
- objProducts.Manufacturer = row["Manufacturer"].ToString();
- objProducts.Price = Convert.ToDecimal(row["Price"]);
- objProducts.Stock = Convert.ToInt32(row["Stock"]);
-
- listProducts.Add(objProducts);
- }
-
- var jsonResult = Json(listProducts, JsonRequestBehavior.AllowGet);
- jsonResult.MaxJsonLength = int.MaxValue;
- return jsonResult;
- }
Step 4
a. Go to your View, where you want to display the Grid. Create a table with the following format-
- <table id="GridView" class="display" width="100%">
- <thead>
- <tr>
- <th>Product ID</th>
- <th>Product Name</th>
- <th>Manufacturer</th>
- <th>Price</th>
- <th>Stock</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody></tbody>
- </table>
b. Place jQuery and DataTable, given below, plugin inside Head Tag-
- < link href = "https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"
- rel = "stylesheet" / >
- < script href = "https://code.jquery.com/jquery-1.12.3.js" > < /script> < script src = "https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" >
- < /script>
c. Place the code, given below, inside the script-
- <script type="text/javascript">
- $(document).ready(function() {
- $('#GridView').dataTable({
- "bPaginate": true,
- "autoWidth": false,
- "sPaginationType": "full_numbers",
- "order": [
- [0, "asc"],
- [1, 'asc']
- ],
- "bFilter": true,
- "iDisplayLength": 20,
- "lengthMenu": [
- [10, 20, 50, 100, -1],
- [10, 20, 50, 100, "All"]
- ],
- "ajax": {
- "type": "POST",
- "dataType": 'json',
- "url": "@Url.Action("
- GetProductList ", "
- Home ")"
- },
- "columns": [{
- "data": "ProdID"
- }, {
- "data": "ProdName"
- }, {
- "data": "Manufacturer"
- }, {
- "data": "Price"
- }, {
- "data": "Stock"
- }, {
- "data": "ProdID"
- }],
- "aoColumnDefs": [{
- "aTargets": [5],
- "fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
- $(nTd).empty();
- $(nTd).append(" <
- button title = \"Edit Record\" onclick=\ "
- EditField('" + oData.ProdID + "', '" + oData.ProdName + "')\
- "></button>" + " <
- button title = \"Delete Record\" onclick=\ "
- DeleteField(''
- " + oData.ProdID + "
- ','
- " + oData.ProdName + "
- ')\"></button>"); } }, ] }); }); function EditField(prodID,prodName) {
- </script>
You will get a grid with product list, along with each row. You will get an Edit and a Delete button, which calls EditField() and DeleteField() JS method respectively.
Write your own JS code to edit and delete the selected record. This is to inform you that the “ProdID” is being sent from the button to the function. Call your back-end function to edit and delete the record, based on “ProdID”.
How can you call a back-end function from jQuery ? Read my previous article, whose link is given below-
There are many attractive features, which you will get inDataTable. In this article, I explained the basic features of DataTable.
You can export the displayed record into PDF, Excel, CSV. Can you imagine? It is very simple! Add one line of code. That's it.
To know how to export, please visit the below mentioned
blog or else wait for my next article and meanwhile practice this by developing demo projects.
Thank you for reading this blog.