Beginners Guide to Create Grid in ASP.NET MVC 5 using JQuery DataTables

Introduction

In this post, we will be seeing how we can create a grid view in asp.net mvc, same like we have in asp.net web form. There are many their party both server side and also client side plugins written in JQuery are available which provide all the essential functionalities that we have in web forms which include searching, sorting and paging etc. It totally depends on the requirements of specific application if the search is needed client side or server side, same for the other functions.

You can download the sample solution from MSDN gallery at this link.

Few Available Libraries

Some of the libraries and plugins available are:

Using JQuery DataTables

All have their pros and cons, but personally I have found jQuery datatables to be a good choice. It is highly flexible. It supports pagination, instant-search, multi-column ordering. It also supports almost all the data sources to which it can be bound, some of which are:

One of the best option which I like in it is that it supports both client side searching, pagination, sorting etc, but it also provides option to have server side processing of it, as there can be case where we have too much data in database and in that case client side paging wouldn’t be a good option, just think millions of rows in a table and if they are bound to it using client side pagination, it will make or page unresponsive due to high amount of rows processing and html rendering.

We will first see an example of how we can implement it using client side processing. So, let’s get started. We will have a working grid with searching, sorting and paging at the end of the post which will look like:

Database Creation

First of all create database and table that we will be using in this post, Open SQL Management Studio and run the following script:

1.  CREATE DATABASE [GridExampleMVC]  

2.  GO  

3.    

4.  CREATE TABLE [dbo].[Assets] (  

5.      [AssetID]                   UNIQUEIDENTIFIER NOT NULL,  

6.      [Barcode]                   NVARCHAR (MAX)   NULL,  

7.      [SerialNumber]              NVARCHAR (MAX)   NULL,  

8.      [FacilitySite]              NVARCHAR (MAX)   NULL,  

9.      [PMGuide]                   NVARCHAR (MAX)   NULL,  

10.     [AstID]                     NVARCHAR (MAX)   NOT NULL,  

11.     [ChildAsset]                NVARCHAR (MAX)   NULL,  

12.     [GeneralAssetDescription]   NVARCHAR (MAX)   NULL,  

13.     [SecondaryAssetDescription] NVARCHAR (MAX)   NULL,  

14.     [Quantity]                  INT              NOT NULL,  

15.     [Manufacturer]              NVARCHAR (MAX)   NULL,  

16.     [ModelNumber]               NVARCHAR (MAX)   NULL,  

17.     [Building]                  NVARCHAR (MAX)   NULL,  

18.     [Floor]                     NVARCHAR (MAX)   NULL,  

19.     [Corridor]                  NVARCHAR (MAX)   NULL,  

20.     [RoomNo]                    NVARCHAR (MAX)   NULL,  

21.     [MERNo]                     NVARCHAR (MAX)   NULL,  

22.     [EquipSystem]               NVARCHAR (MAX)   NULL,  

23.     [Comments]                  NVARCHAR (MAX)   NULL,  

24.     [Issued]                    BIT              NOT NULL,  

25.     CONSTRAINT [PK_dbo.Assets] PRIMARY KEY CLUSTERED ([AssetID] ASC)  

26. )  

27. GO    

There is complete sql script file attached in the source code, so we can use it to create the database and table with sample data.

Setting Up Project

Now, create a new asp.net mvc 5 web application. Open Visual Studio 2015. Go to File >> New >> Project

From the dialog navigate to Web and select ASP.Net Web Application project and click OK.

From Templates, Select MVC, check the unit tests if we will write unit tests as well for our implementations and click OK.

Our project is created with basic things in place for us. Now we will start by creating the database context class as we will be using Entity Framework for the Data Access.

First of all we need to create model for the Asset table which we will be using for retrieving data using ORM.

Adding Model Class

In Model folder, create a new class named Asset:

using System.ComponentModel.DataAnnotations;
 
namespace GridExampleMVC.Models
 
{
 
    public class  Asset
 
    {
 
        public System.Guid AssetID { get; set; }
 
        [Display(Name = "Barcode")]
 
        public string  Barcode { get; set; }
 
        [Display(Name = "Serial-Number")]
 
        public string  SerialNumber { get; set; }
 
        [Display(Name = "Facility-Site")]
 
        public string  FacilitySite { get; set; }
 
        [Display(Name = "PM-Guide-ID")]
 
        public string  PMGuide { get; set; }
 
        [Required]
 
        [Display(Name = "Asset-ID")]
 
        public string  AstID { get; set; }
 
        [Display(Name = "Child-Asset")]
 
        public string  ChildAsset { get; set; }
 
        [Display(Name = "General-Asset-Description")]
 
        public string  GeneralAssetDescription { get; set; }
 
        [Display(Name = "Secondary-Asset-Description")]
 
        public string  SecondaryAssetDescription { get; set; }
 
        public int  Quantity { get; set; }
 
        [Display(Name = "Manufacturer")]
 
        public string  Manufacturer { get; set; }
 
        [Display(Name = "Model-Number")]
 
        public string  ModelNumber { get; set; }
 
        [Display(Name = "Main-Location (Building)")]
 
        public string  Building { get; set; }
 
        [Display(Name = "Sub-Location 1 (Floor)")]
 
        public string  Floor { get; set; }
 
        [Display(Name = "Sub-Location 2 (Corridor)")]
 
        public string  Corridor { get; set; }
 
        [Display(Name = "Sub-Location 3 (Room No)")]
 
        public string  RoomNo { get; set; }
 
        [Display(Name = "Sub-Location 4 (MER#)")]
 
        public string  MERNo { get; set; }
 
        [Display(Name = "Sub-Location 5 (Equip/System)")]
 
        public string  EquipSystem { get; set; }
 
        public string  Comments { get; set; }
 
        public bool  Issued { get; set; }
 
    }
 
}

Entity Framework Mapping for Table

Now Navigate to Models folder from Solution Explorer and open IdenityModels.cs file , we will add a property for the Asset table in the database context, which will be the Entity Framework representation of Asset table which we created using the script. Add new property in the ApplicationDbContext class:

public class  ApplicationDbContext : IdentityDbContext<ApplicationUser>
 
{
 
    public ApplicationDbContext()
 
        : base("DefaultConnection", throwIfV1Schema: false)
 
    {
 
    }
 
    public DbSet<Asset> Assets { get; set; }
 
    public static  ApplicationDbContext Create()
 
    {
 
        return new  ApplicationDbContext();
 
    }
 
}

The above is the default entity framework settings for asp.net identity 2.0, we are extending it with our own tables for which we have added new DbSet for Asset table.

Adding Controller

Now add an empty controller in Controllers folder named AssetController, which we will be using for all the Asset related work. Here is how it should look like:

public class  AssetController : Controller
 
    {
 
        // GET: Asset
 
        public ActionResult Index()
 
        {
 
            return View();
 
        }
 
    }

Installing JQuery DataTables via NuGet

Now we will install jQuery datatables that we will be using to build the grid, Go to Tools >> NuGet Package Manager >> Manage Nuget Packages for Solution and click it.

The package manager will get opened and by default it will be displaying the installed nugget packages in our solution, click the browser button and then search for jQuery datatables package, then select it and check the projects of the solution in which we want to install this package, in our case we are installing in it GridExampleMVC web project only as per requirement and then press the install button.

Visual Studio will prompt to tell that it is going to modify the solution, we will have to press ok to continue the installation of the package.

Bundling the css and js files

After the Nuget package is installed successfully, we need to include the necessary js and css of jquery datatables in the view where we will use it, for that we have to register the jquery datatables, for that open the BundleConfig.cs file locate in App_Start folder and add the following code for css and js files at the end:

bundles.Add(new ScriptBundle("~/bundles/datatables").Include(
 
                        "~/Scripts/DataTables/jquery.dataTables.min.js",
 
                        "~/Scripts/DataTables/dataTables.bootstrap.js"));
 
bundles.Add(new StyleBundle("~/Content/datatables").Include(
 
          "~/Content/DataTables/css/dataTables.bootstrap.css"));

After registering the scripts and css for datatables, we need to add them in our master layout which is by default _Layout.cshtml located in Views >> Shared which is defined in the _ViewStart.cshtml located in the same location.

Before writing the controller code, we need to configure the connection string for entity framework that will be used to connect database when it will be doing database operations i.e. running queries. So our connection string should be pointing to a valid data source so that our application won’t break when we run it.

Setting Up Connection String for Database Connection

For that open web.config and provide the connection string for the database. In config file we will find the under configurations node connectionStrings, we will need to modify the connection string in that node according to our system. In my case it looks like:

<connectionStrings>
 
    <add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=GridExampleMVC;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
 
  </connectionStrings>

Implementing Controller Action

Now in controller add a property for database context that we will be using for querying the database.

private ApplicationDbContext _dbContext;
 
public ApplicationDbContext DbContext
 
{
 
    get
 
    {
 
        return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
 
    }
 
    private set
 
    {
 
        _dbContext = value;
 
    }
 
}

This property we will be using to query the database with entity framework in all actions of the controller wherever needed.

Now in the index action, we will simply fetch all the rows of the table and pass it to view:

public ActionResult Index()
 
{
 
    return View(DbContext.Assets.ToList());
 
}
 
Our complete controller class  code now looks like:
 
using GridExampleMVC.Models;
 
using System.Linq;
 
using System.Web;
 
using System.Web.Mvc;
 
using Microsoft.AspNet.Identity.Owin;
 
namespace GridExampleMVC.Controllers
 
{
 
    public class  AssetController : Controller
 
    {
 
        private ApplicationDbContext _dbContext;
 
        public ApplicationDbContext DbContext
 
        {
 
            get
 
            {
 
                return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
 
            }
 
            private set
 
            {
 
                _dbContext = value;
 
            }
 
        }
 
        public AssetController()
 
        {
 
        }
 
        public AssetController(ApplicationDbContext dbContext)
 
        {
 
            _dbContext = dbContext;
 
        }
 
        // GET: Asset
 
        public ActionResult Index()
 
        {
 
            return View(DbContext.Assets.ToList());
 
        }
 
    }
 
}

View Implementation with DataTables Initialization

Here comes the view part now, where we will write code about how it should render as html. So create a view with Template Empty (Without Model) for the Index action and add the following code in it:

@model IEnumerable< GridExampleMVC.Models.Asset>
 
<div class="row">
 
    <div class="col-md-12">
 
        <div class="panel panel-primary list-panel" id="list-panel">
 
            <div class="panel-heading list-panel-heading">
 
                <h1 class="panel-title list-panel-title">Assets</h1>
 
            </div>
 
            <div class="panel-body">
 
                <table id="assets-data-table" class="table table-striped table-bordered" style="width:100%">
 
                    <thead>
 
                        <tr>
 
                            <th>Bar Code</th>
 
                            <th>Manufacturer</th>
 
                            <th>Model Number</th>
 
                            <th>Building</th>
 
                            <th>Room No</th>
 
                            <th>Quantity</th>
 
                        </tr>
 
                    </thead>
 
                    <tbody>
 
                        @foreach (var asset in Model)
 
                        {
 
                            <tr>
 
                                <td>@asset.Barcode</td>
 
                                <td>@asset.Manufacturer</td>
 
                                <td>@asset.ModelNumber</td>
 
                                <td>@asset.Building</td>
 
                                <td>@asset.RoomNo</td>
 
                                <td>@asset.Quantity</td>
 
                            </tr>
 
                        }
 
                    </tbody>
 
                </table>
 
            </div>
 
        </div>
 
    </div>
 
</div>
 
@section Scripts
 
{
 
    
 
 <script type="text/javascript">
 
     $(document).ready(function () {
 
         $('#assets-data-table').DataTable();
 
     });
 
    </script>  
 
    
 
 }

Point to Note

Now run the application and we will see a grid with sorting, searching and filtering available in it, but there is one problem in it, which is it is processed on client side, all the data is rendered by view when action is called which may make page performance slow or increases page load time if there are a large number of rows coming.

We will be seeing in another post how we can make it more better by using server side paging, sorting and filtering which is surely a better approach where we have huge data set and we don't want to load all of them in browser memory at page load.