Sunday, 16 July 2017

Bind data in MVC using Datatables.net Jquery Plugin

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table. DataTables is a table enhancing library which adds features such as paging, ordering, search, scrolling and many more to a static HTML page. A comprehensive API is also available that can be used to manipulate the table.
 Reference taken : http://csharp-video-tutorials.blogspot.com/2015/08/jquery-datatables-get-data-from.html

In Controller Action Methods.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace MvcApplication3.Controllers
{
    public class homeController : Controller
    {
        public ActionResult Index()
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            List<Employee> employees = new List<Employee>();
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetEmployees", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Employee employee = new Employee();
                    employee.Id = Convert.ToInt32(rdr["Id"]);
                    employee.FirstName = rdr["FirstName"].ToString();
                    employee.LastName = rdr["LastName"].ToString();
                    employee.Gender = rdr["Gender"].ToString();
                    employee.JobTitle = rdr["JobTitle"].ToString();
                    employee.WebSite = rdr["WebSite"].ToString();
                    employee.Salary = Convert.ToInt32(rdr["Salary"]);
                    employee.HireDate = Convert.ToDateTime(rdr["HireDate"]);
                    employees.Add(employee);
                }
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            string JSONString = js.Serialize(employees);

            ViewBag.datast = JSONString;
            return View();
        }  
    }
}

In Index.cshtml view

@{
    Layout = null;
}

<link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.css" />
<link rel="stylesheet" type="text/css"
    href="https://cdn.datatables.net/1.10.15/css/dataTables.semanticui.min.css" />



<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.2/js/dataTables.select.min.js"></script>
<script src="../../extensions/Editor/js/dataTables.editor.min.js"></script>
<script src="../../extensions/Editor/js/editor.semanticui.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
       
        var dataset =@Html.Raw((String)ViewBag.datast)

        $('#datatable').dataTable({
            edit: true,
            data: dataset,
        columns: [
                    { 'data': 'Id' },
                    { 'data': 'FirstName' },
                    { 'data': 'LastName' },
                    { 'data': 'Gender' },
                    { 'data': 'JobTitle' },
                    {
                        'data': 'WebSite',
                        'sortable': false,
                        'searchable': false,
                        'render': function (webSite) {
                            if (!webSite) {
                                return 'N/A';
                            }
                            else {
                                return '<a href=' + webSite + '>'
                                    + webSite.substr(0, 10) + '...' + '</a>';
                            }
                        }
                    },
                    {
                        'data': 'Salary',
                        'render': function (salary) {
                            return "$" + salary;
                        }
                    },
                    {
                        'data': 'HireDate',
                        'render': function (jsonDate) {
                            var date = new Date(parseInt(jsonDate.substr(6)));
                            var month = date.getMonth() + 1;
                            return month + "/" + date.getDate() + "/" + date.getFullYear();
                        }
                    }
        ]


    });
    });
</script>


<div style="width: 900px; border: 1px solid black; padding: 3px">
    <table id="datatable" class="ui celled table" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Job Title</th>
                <th>Web Site</th>
                <th>Salary</th>
                <th>Hire Date</th>
            </tr>
        </thead>
    </table>
</div>

No comments:

Post a Comment