Skip to main content

Generic Table view with sorting and paging using Jquery in MVC

Objectives 

1. you can create a view which can be used for any modal and show its value in grid type
2. In this given code client side jquery makes sorting and paging at client side  


Step1 : Create Controller 



    public class CustomGridDemoController : Controller
    {
        // GET: CustomGridDemo
        public ActionResult Index()
        {
            SuperDogs sd = new SuperDogs();
            dynamic charts = sd.GetHardCodedValues();
            return View(charts);
        }
       //New any class
        public ActionResult myfunc()
        {
            SampleClass sd = new SampleClass();
            dynamic charts = sd.GetHardCodedValues();
            return View("Index",charts);
        }

    }

Step2 : Create Classes According to your need


    public class SuperDogs
    {
        public string DogName { get; set; }
        public string BreedName { get; set; }
        public int DogAge { get; set; }
        public string DogOwner { get; set; }
        /// <summary>
        /// This returns the hard code values required for setting the grid
        /// </summary>
        /// <returns></returns>
        public List<SuperDogs> GetHardCodedValues()
        {
            var returnModel = new List<SuperDogs>();

            var firstDog = new SuperDogs
            {
                BreedName = "Labrador",
                DogAge = 1,
                DogName = "HACHIKO",
                DogOwner = "SURAJ SAHOO",

            };

            var secondDog = new SuperDogs
            {
                BreedName = "Labrador",
                DogAge = 2,
                DogName = "STEFFY",
                DogOwner = "XYZ",
            };
            var thirdDog = new SuperDogs
            {
                BreedName = "Golden Retriever",
                DogAge = 3,
                DogName = "LOVELY",
                DogOwner = "PQrS",
            };
            var forthDog = new SuperDogs
            {
                BreedName = "German Spitz",
                DogAge = 5,
                DogName = "CANDY",
                DogOwner = "ABCD",
            };
            var fifthDog = new SuperDogs
            {
                BreedName = "German Sheperd",
                DogAge = 10,
                DogName = "CAPTAIN",
                DogOwner = "Mota",
            };
            var sixthDog = new SuperDogs
            {
                BreedName = "British BullDog",
                DogAge = 10,
                DogName = "BILL",
                DogOwner = "AUTA",
            };
            for (var i = 0; i < 10; i++)
            {
                returnModel.Add(firstDog);
                returnModel.Add(secondDog);
                returnModel.Add(thirdDog);
                returnModel.Add(forthDog);
                returnModel.Add(fifthDog);
                returnModel.Add(sixthDog);
            }
            return returnModel;
        }
    

    }
    public class SampleClass
    {
        public string name { get; set; }
        public string Address { get; set; }
        public int Age { get; set; }
        public string Owner { get; set; }
        public string CoOwner { get; set; }
        /// <summary>
        /// This returns the hard code values required for setting the grid
        /// </summary>
        /// <returns></returns>
        public List<SampleClass> GetHardCodedValues()
        {
            var returnModel = new List<SampleClass>();

            var firstDog = new SampleClass
            {
                name = "abc",
                Age = 1,
                Address = "HACHIKO",
                Owner = "SAHOOkar",
                CoOwner = "SURAJ SAHOO",

            };

            var secondDog = new SampleClass
            {
                name = "bcd",
                Age = 1,
                Address = "ktml",
                Owner = "Master",
                CoOwner = "SURAJ SAHOO",
            };
            var thirdDog = new SampleClass
            {
                name = "cde",
                Age = 1,
                Address = "zxcc",
                Owner = "manik rao",
                CoOwner = "SURAJ SAHOO",
            };
            var forthDog = new SampleClass
            {
                name = "zde",
                Age = 1,
                Address = "adfk",
                Owner = "abhi",
                CoOwner = "SURAJ SAHOO",
            };
            var fifthDog = new SampleClass
            {
                name = "def",
                Age = 1,
                Address = "kamio",
                Owner = "Ramdev",
                CoOwner = "SURAJ SAHOO",
            };
            var sixthDog = new SampleClass
            {
                name = "EFG",
                Age = 1,
                Address = "mcd",
                Owner = "SURAJ ",
                CoOwner = "SURAJ SAHOO",
            };
            for (var i = 0; i < 10; i++)
            {
                returnModel.Add(firstDog);
                returnModel.Add(secondDog);
                returnModel.Add(thirdDog);
                returnModel.Add(forthDog);
                returnModel.Add(fifthDog);
                returnModel.Add(sixthDog);
            }
            return returnModel;
        }


    }

Step3 : Create View or partial view according to you


@model IEnumerable<dynamic>
@using System.Reflection;

<div class="leftPanel">
    <div class="spacerBody">
        <div class="table">
            <table id="empTable" class="table table-bordered">
                <thead>
                    <tr>
                        @foreach (var item in Model)
                        {
                            var marry = item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                            foreach (var items in marry)
                            {
                                <th>@items.Name &nbsp;&nbsp;&nbsp;&nbsp;</th>
                            }
                            break;
                        }
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            @foreach (var items in item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                            {
                                <td>@items.GetValue(item, null) &nbsp;&nbsp;&nbsp;&nbsp;</td>
                            }
                        </tr>
                    }
                </tbody>

</table>
            <div>
                <a href="#" class="paginate" id="previous">Previous</a> |
                <a href="#" class="paginate" id="next">Next</a>
            </div>
            </div>
        </div>
    </div>
<script type='text/javascript' src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" ></script>
<script type='text/javascript'>
    
    $(function () {
        // Selectors for future use
        var myTable = "#empTable";
        var myTableBody = myTable + " tbody";
        var myTableRows = myTableBody + " tr";
        var myTableColumn = myTable + " th";

        // Starting table state
        function initTable() {

            // Increment the table width for sort icon support
            $(myTableColumn).each(function () {
                var width = $(this).width();
                $(this).width(width + 40);
            });

            // Set the first column as sorted ascending
            $(myTableColumn).eq(0).addClass("sorted-asc");

            //Sort the table using the current sorting order
            sortTable($(myTable), 0, "asc");

        }

        // Table starting state
        initTable();

        // Table sorting function
        function sortTable(table, column, order) {
            var asc = order === 'asc';
            var tbody = table.find('tbody');

            // Sort the table using a custom sorting function by switching
            // the rows order, then append them to the table body
            tbody.find('tr').sort(function (a, b) {
                if (asc) {
                    return $('td:eq(' + column + ')', a).text()
                        .localeCompare($('td:eq(' + column + ')', b).text());
                } else {
                    return $('td:eq(' + column + ')', b).text()
                        .localeCompare($('td:eq(' + column + ')', a).text());
                }
            }).appendTo(tbody);

        }

        // Heading click
        $(myTableColumn).click(function () {

            // Remove the sort classes for all the column, but not the first
            $(myTableColumn).not($(this)).removeClass("sorted-asc sorted-desc");

            // Set or change the sort direction
            if ($(this).hasClass("sorted-asc") || $(this).hasClass("sorted-desc")) {
                $(this).toggleClass("sorted-asc sorted-desc");
            } else {
                $(this).addClass("sorted-asc");
            }

            //Sort the table using the current sorting order
            sortTable($(myTable),
                        $(this).index(),
                        $(this).hasClass("sorted-asc") ? "asc" : "desc");

        });

    });
    $(function () {
        // Selectors for future use
        var myTable = "#empTable";
        var myTableBody = myTable + " tbody";
        var myTableRows = myTableBody + " tr";
        var myTableColumn = myTable + " th";
        // Starting table state
        function initTable() {
            $(myTableBody).attr("data-pageSize", 4);
            $(myTableBody).attr("data-firstRecord", 0);
            $('#previous').hide();
            $('#next').show();
            // Increment the table width for sort icon support
            // Start the pagination
            paginate(parseInt($(myTableBody).attr("data-firstRecord"), 10),
                     parseInt($(myTableBody).attr("data-pageSize"), 10));
        }
        // Table sorting function
       
        // Heading click
        $(myTableColumn).click(function () {
            // Start the pagination
            paginate(parseInt($(myTableBody).attr("data-firstRecord"), 10),
                     parseInt($(myTableBody).attr("data-pageSize"), 10));
        });
        // Pager click
        $("a.paginate").click(function (e) {
            e.preventDefault();
            var tableRows = $(myTableRows);
            var tmpRec = parseInt($(myTableBody).attr("data-firstRecord"), 10);
            var pageSize = parseInt($(myTableBody).attr("data-pageSize"), 10);
            // Define the new first record
            if ($(this).attr("id") == "next") {
                tmpRec += pageSize;
            } else {
                tmpRec -= pageSize;
            }
            // The first record is < of 0 or > of total rows
            if (tmpRec < 0 || tmpRec > tableRows.length) return
            $(myTableBody).attr("data-firstRecord", tmpRec);
            paginate(tmpRec, pageSize);
        });
        // Paging function
        var paginate = function (start, size) {
            var tableRows = $(myTableRows);
            var end = start + size;
            // Hide all the rows
            tableRows.hide();
            // Show a reduced set of rows using a range of indices.
            tableRows.slice(start, end).show();
            // Show the pager
            $(".paginate").show();
            // If the first row is visible hide prev
            if (tableRows.eq(0).is(":visible")) $('#previous').hide();
            // If the last row is visible hide next 
            if (tableRows.eq(tableRows.length - 1).is(":visible")) $('#next').hide();
        }
        // Table starting state
        initTable();
    });
</script>


If  you have any Query , you can comment me any time i will revert asap
For download use this link ...

Comments

Popular posts from this blog

Claims Class For security in .NET4.5 with C#

What is Claim ? A claim in the world of authentication and authorization can be defined as a statement about an entity, typically a user. A claim can be very fine grained: Ram is an admin Ram’s email address is Ram@yahoo.com Ram lives in Mumbai Tom’s allowed to view sales figures between 2009 and 2012 Tom’s allowed to wipe out the universe Claims originate from a trusted entity other than the one that is being described. This means that it is not enough that Tom says that he is an administrator. If your company’s intranet runs on Windows then Tom will most likely figure in Active Directory/Email server/Sales authorisation system and it will be these systems that will hold these claims about Tom.  The idea is that if a trusted entity such as AD tells us things about Tom then we believe them a lot more than if Tom himself comes with the same claims . This external trusted entity is called an  Issuer . The KEY in the key-value pairs is called a  Typ...

Paytm integration

How to integrate Paytm to asp.net site   You will need to create an Checksum on your server. Kindly refer the dll file for the attachment.  Usage of CheckSum API: ·         Add provided “paytm.dll” as a “Reference” in your project. ·         Import namespace “paytm” in your Class with statement “using paytm”. ·         Now Generate CheckSum API as well as Verify CheckSum API are available as follows: o   String CheckSum.generateCheckSum(String masterKey, Dictionary<String, String> parameters) o   Boolean CheckSum.verifyCheckSum(String masterKey, Dictionary<String, String> parameters, StringcheckSum) ·         For Generating CheckSum, use following snippet code: String masterKey = “merchantKey” ; Dictionary<String, String> parameters = new Dictionary<string, string>(); p...

Javascript ECMAScript6 New Feature

Extended Parameter Handling Another nice set of features introduced in ES6 is the extended parameter handling. These provide a very nice set of idioms that bring us very close to languages like C# or Java. Default parameter values and optional parameters Default parameters allow your functions to have optional arguments without needing to check arguments.length or check for undefined. Let’s take a look at what that might look like: let greet = (msg = 'hello', name = 'world') => {   console.log(msg,name); } greet(); greet('hey'); Looking at the preceding code, you can see that we are using the new fat arrow (=>) syntax as well as the new let keyword. Neither of those are necessary for this example, but I added it to give you more exposure to the new syntax. Running the preceding code produces the following result: hello world hey world  Rest parameter Handling a function with a variable number of arguments is always t...