Click here to Skip to main content
15,880,967 members
Articles / Web Development / HTML

Beginners Guide for Creating GridView in ASP.NET MVC 5

Rate me:
Please Sign up or sign in to vote.
4.67/5 (35 votes)
14 Jun 2017CPOL7 min read 192.3K   2.6K   78   43
A guide on how to implement gridview in ASP.NET MVC 5

Introduction

In this post, we will be seeing how we can create a gridview in ASP.NET MVC, same like we have in ASP.NET web form. There are many third party both server side and client side soltuions 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 source code from this link.

Libraries Available

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 binded, some of which are:

One of the best options which I like in it is that it supports both client side searching, pagination, sorting, etc. but it also provides an option to have server side processing of it, as there can be a 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 binded to it using client side pagination, it will make our 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:

Image 1

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

SQL
CREATE DATABASE [GridExampleMVC]  
 GO  
   
 CREATE TABLE [dbo].[Assets] (  
     [AssetID]                   UNIQUEIDENTIFIER NOT NULL,  
     [Barcode]                   NVARCHAR (MAX)   NULL,  
     [SerialNumber]              NVARCHAR (MAX)   NULL,  
     [FacilitySite]              NVARCHAR (MAX)   NULL,  
     [PMGuide]                   NVARCHAR (MAX)   NULL,  
     [AstID]                     NVARCHAR (MAX)   NOT NULL,  
     [ChildAsset]                NVARCHAR (MAX)   NULL,  
     [GeneralAssetDescription]   NVARCHAR (MAX)   NULL,  
     [SecondaryAssetDescription] NVARCHAR (MAX)   NULL,  
     [Quantity]                  INT              NOT NULL,  
     [Manufacturer]              NVARCHAR (MAX)   NULL,  
     [ModelNumber]               NVARCHAR (MAX)   NULL,  
     [Building]                  NVARCHAR (MAX)   NULL,  
     [Floor]                     NVARCHAR (MAX)   NULL,  
     [Corridor]                  NVARCHAR (MAX)   NULL,  
     [RoomNo]                    NVARCHAR (MAX)   NULL,  
     [MERNo]                     NVARCHAR (MAX)   NULL,  
     [EquipSystem]               NVARCHAR (MAX)   NULL,  
     [Comments]                  NVARCHAR (MAX)   NULL,  
     [Issued]                    BIT              NOT NULL,  
     CONSTRAINT [PK_dbo.Assets] PRIMARY KEY CLUSTERED ([AssetID] ASC)  
 )  
 GO

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

Now, create a new ASP.NET MVC 5 web application. Open Visual Studio 2015. Go to File >> New >> Project.

Image 2

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

Image 3

From Templates, select MVC, check the unit tests if you will write unit tests as well for your 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.
In Model folder, create a new class named Asset:

C#
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; }
    }
}

Now navigate to Models folder from Solution Explorer and open IdentityModels.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:

C#
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.

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:

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

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

Image 4

The package manager will get opened and by default, it will be displaying the installed nugget packages in your solution, click the browser button and then search for jQuery datatables package, then select it and check the projects of the solution in which you 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.

Image 5

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

After the nugget 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 located in App_Start folder and add the following code for css and js files at the end:

C#
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.

Image 6

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.

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

XML
<connectionstrings>
    <add connectionstring="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=GridExampleMVC;
     Integrated Security=True;MultipleActiveResultSets=true" name="DefaultConnection" 
     providername="System.Data.SqlClient"/>
</connectionstrings>

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

C#
private ApplicationDbContext _dbContext;

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

We will be using this property 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:

C#
public ActionResult Index()
{
    return View(DbContext.Assets.ToList());
}

Our complete controller class code now looks like:

C#
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());
        }
    }
}

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:

HTML
@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>       
 }

Now run the application and you 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 better by using server side paging, sorting and filtering which is surely a better approach where we have a huge data set.

Server Side Processing 

There is another article which is a follow up of this article in which we talked about how we can implement grid view with server side processing for searching, sorting and filtering, if you are interested to do server side processing as in most of the case where we have big volume of data we never want to bring all data on client side because user will not be looking for all the data but some specific data, so server side processing will make things better. You can read the article at following link:

GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5

Advanced Search

There is another article in this series which talks about how to add Advanced Search in this server side JQuery DataTables processing, as right now single textbox is being used which is searching through all the columns of the Grid or the columns we specified it to search in, but sometimes we need more robust search by applying different search criterias on each column which this articles demonstrates how to do it:

Grid with Server Side Advanced Search using JQuery DataTables in ASP.NET MVC 5

Ajax CRUD Operation Support

There is another article which elaborates how CRUD operations can be implemened within the gird that we created using JQuery DataTables, i wrote about this as couple of guys asked in commments on previous articles that how they can add hyperlinks for update, delete in the gird, following is the link to the article:

 Beginners Guide on Implementing AJAX CRUD in Grid with Jquery DataTables in ASP.NET MVC 5

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Ehsan Sajjad is a Microsoft Certified Professional, Microsoft Certified C# Specialist and he is also among the top users on StackOverflow from Pakistan with 50k+ reputation at time of writing this and counting.

He is a passionate software developer with around 5 years of professional experience in Microsoft Technologies both web and desktop applications and always open to learn new things and platforms especially in mobile application development and game development.

Some Achievements :

  • 5th Top Contributor from Pakistan on Stackoverflow.com
  • Top User in ASP.NET MVC from Pakistan on Stackoverflow.com
  • 21st June 2017 - Article of the Day - ASP.NET Community (Beginners Guide on AJAX CRUD Operations in Grid using JQuery DataTables in ASP.NET MVC 5)
  • 19th April 2017 - Article of the Day - ASP.NET Community (ASP.NET MVC Async File Uploading using JQuery)
  • March 2017 - Visual C# Technical Guru Silver Medal on Microsoft Tech Net Wiki Article Competition
  • 20 January 2017 - Article of the Day - ASP.NET Community (Async File Uploading in ASP.NET MVC)
  • 22nd September 2016 - Article of the Day - ASP.NET Community (GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5)
  • 22nd August 2016 - Article of the Day - ASP.NET Community (Beginners Guide for Creating GridView in ASP.NET MVC 5)
  • December 2015 - C-SharpCorner Monthly Winner

Comments and Discussions

 
GeneralMy vote of 5 Pin
Oğuz Çelikdemir1-Apr-24 21:55
Oğuz Çelikdemir1-Apr-24 21:55 
GeneralRe: My vote of 5 Pin
Ehsan Sajjad2-Apr-24 9:39
professionalEhsan Sajjad2-Apr-24 9:39 
Questionawesome Pin
imransaharp1-Oct-19 21:14
imransaharp1-Oct-19 21:14 
GeneralMy vote of 1 Pin
MSDEVTECHNIK26-Jul-19 5:26
MSDEVTECHNIK26-Jul-19 5:26 
GeneralRe: My vote of 1 Pin
Ehsan Sajjad28-Jul-19 21:08
professionalEhsan Sajjad28-Jul-19 21:08 
Question_Layout.schtml Pin
Da'mon Ferguson14-Dec-18 11:57
professionalDa'mon Ferguson14-Dec-18 11:57 
AnswerRe: _Layout.schtml Pin
Ehsan Sajjad30-Sep-19 19:47
professionalEhsan Sajjad30-Sep-19 19:47 
PraiseVery well written Pin
hdi.amiri6-Dec-17 9:57
hdi.amiri6-Dec-17 9:57 
GeneralRe: Very well written Pin
Ehsan Sajjad6-Dec-17 23:41
professionalEhsan Sajjad6-Dec-17 23:41 
QuestionPagination, sorting not displaying Pin
Minaz Hirji7-Jul-17 7:41
Minaz Hirji7-Jul-17 7:41 
AnswerRe: Pagination, sorting not displaying Pin
Ehsan Sajjad7-Jul-17 8:41
professionalEhsan Sajjad7-Jul-17 8:41 
AnswerRe: Pagination, sorting not displaying Pin
Member 127649716-Oct-17 6:46
Member 127649716-Oct-17 6:46 
GeneralRe: Pagination, sorting not displaying Pin
Member 110456639-Jul-19 9:01
Member 110456639-Jul-19 9:01 
GeneralMy vote of 5 Pin
raddevus23-May-17 2:39
mvaraddevus23-May-17 2:39 
GeneralRe: My vote of 5 Pin
Ehsan Sajjad23-May-17 2:49
professionalEhsan Sajjad23-May-17 2:49 
QuestionTrying to display two grids on one page Pin
Tony Girgenti12-May-17 9:42
Tony Girgenti12-May-17 9:42 
AnswerRe: Trying to display two grids on one page Pin
Ehsan Sajjad12-May-17 10:25
professionalEhsan Sajjad12-May-17 10:25 
GeneralRe: Trying to display two grids on one page Pin
Tony Girgenti12-May-17 11:34
Tony Girgenti12-May-17 11:34 
GeneralRe: Trying to display two grids on one page Pin
Ehsan Sajjad15-May-17 0:57
professionalEhsan Sajjad15-May-17 0:57 
GeneralRe: Trying to display two grids on one page Pin
Tony Girgenti15-May-17 2:31
Tony Girgenti15-May-17 2:31 
Question5 STARS!! Pin
Member 108621809-May-17 16:03
Member 108621809-May-17 16:03 
AnswerRe: 5 STARS!! Pin
Ehsan Sajjad10-May-17 2:35
professionalEhsan Sajjad10-May-17 2:35 
Question+5 - But A Typo Pin
Kevin Marois8-May-17 11:53
professionalKevin Marois8-May-17 11:53 
AnswerRe: +5 - But A Typo Pin
Ehsan Sajjad9-May-17 0:41
professionalEhsan Sajjad9-May-17 0:41 
QuestionThank you Pin
Member 1091073023-Mar-17 10:48
Member 1091073023-Mar-17 10:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.