A Simple Way to Implement Grid Using MVC

Introduction
 
This article shows the use Grid.MVC for implementing grids. Grid.MVC adds functionalities for controls like sorting, filtering, paging and many more. This gives an easy way to implement HTML tables containing all the data. This Grid.MVC would require a model that would be an IEnumerable type or collection of data. Here I have used hardcoded values for populating the grid. Now a days many grid sources are available, mainly Telerik Kendo Grid has gained the market, but using this for small applications would be easy and light since we do not need any third-party tool as we can directly install Grid.MVC from the Nuget package that I will be showing below.
 
Let's Get Started

Before getting started, we need to understand what MVC is since everything we are dealing with are MVC components.
 
Step 1
Add a new project to Visual Studio. Select ASP.Net Web Application. Provide a name for it. I have used "MVCGridDemo".

After adding the project, a new pop-up is shown where we need to choose the type like MVC/Web Forms/Web API. We choose MVC here. Now the project is created with sample folders since a MVC project is created. Mainly of focus is Model, View and Controllers folders. The structure looks as in the following:

 
 
Step 2
Now, here we can see the Models, Views and Controllers folder. The next job is to add a controller. So right-click on the controllers folder and add a new controller from the following popup:

 
 
We select the empty controller and name it SuperDogController.cs since we know controllers are suffixed with the controller word.
 
Step 3

Then we add the main part, the Model/ViewModel. Similar to the controller, right-click on the model folder and add a class and name it. Here I have named it SuperDog.cs. The class would look as in the following:



In the preceding image as you can see, I have a Red arrow towards an option called Remove and Sort. What this does is, when we add a class the using statements are added automatically even if they are not being used. So to maintain consistency let's remove them. And we can remove them by right-clicking on the class file and click on the preceding nested route, in other words Remove and Sort, and finally our class SuperDog.cs would look like:
  1. namespace MVCGridDemo.Models  
  2. {  
  3.     public class SuperDogs  
  4.     {  
  5.         public string DogName { getset; }  
  6.         public string BreedName { getset; }  
  7.         public int DogAge { getset; }  
  8.         public string DogOwner { getset; }  
  9.     }  
  10. }  
This is the class we have added after removing or sorting the Usings statements. :)

Step 4

Now its time to add/install the Grid.MVC to our project. In the conext of MVC we would rather say add the Grid.MVC reference to the project. Thus for that we can see Reference in the project structure floating in the route of the web project. We then right-click on that, then seelct Manage Nuget package, then we directly search online for the Grid.MVC, we find the package reference with an install button beside. Click on that and wait for the successful installation of the package.



We should also search for the Bootstrap online and install that too.

Step 5

Now after adding the reference of these two, it's time to add hard coded values for the data collection to be shown in the grid or bound to the grid. The list of the model class data would be added as in the following:
  1. /// <summary>  
  2.        /// This returns the hard code values required for setting the grid  
  3.        /// </summary>  
  4.        /// <returns></returns>  
  5.        public List<SuperDogs> GetHardCodedValues()  
  6.        {  
  7.            var returnModel = new List<SuperDogs>();  
  8.   
  9.            var firstDog = new SuperDogs  
  10.            {  
  11.                BreedName = "Labrador",  
  12.                DogAge = 1,  
  13.                DogName = "HACHIKO",  
  14.                DogOwner = "SURAJ SAHOO",  
  15.                  
  16.            };  
  17.   
  18.            var secondDog = new SuperDogs  
  19.            {  
  20.                BreedName = "Labrador",  
  21.                DogAge = 2,  
  22.                DogName = "STEFFY",  
  23.                DogOwner = "XYZ",  
  24.            };  
  25.            var thirdDog = new SuperDogs  
  26.            {  
  27.                BreedName = "Golden Retriever",  
  28.                DogAge = 3,  
  29.                DogName = "LOVELY",  
  30.                DogOwner = "PQrS",  
  31.            };  
  32.            var forthDog = new SuperDogs  
  33.            {  
  34.                BreedName = "German Spitz",  
  35.                DogAge = 5,  
  36.                DogName = "CANDY",  
  37.                DogOwner = "ABCD",  
  38.            };  
  39.            var fifthDog = new SuperDogs  
  40.            {  
  41.                BreedName = "German Sheperd",  
  42.                DogAge = 10,  
  43.                DogName = "CAPTAIN",  
  44.                DogOwner = "Mota",  
  45.            };  
  46.            var sixthDog = new SuperDogs  
  47.            {  
  48.                BreedName = "British BullDog",  
  49.                DogAge = 10,  
  50.                DogName = "BILL",  
  51.                DogOwner = "AUTA",  
  52.            };  
  53.            for (var i = 0; i < 10; i++)  
  54.            {  
  55.                returnModel.Add(firstDog);  
  56.                returnModel.Add(secondDog);  
  57.                returnModel.Add(thirdDog);  
  58.                returnModel.Add(forthDog);  
  59.                returnModel.Add(fifthDog);  
  60.                returnModel.Add(sixthDog);  
  61.            }  
  62.            return returnModel;  
  63.        }  
The preceding piece of code is added inside the model class SuperDog.cs only.

Step 6

Now the action on the Controller starts. When we double-click and open SuperDogController.cs we can see a default action method of return type ActionResult is already added. Let's add a code block into that method only. Let's add and then look into it line by line:
  1. using MVCGridDemo.Models;  
  2. using System.Collections.Generic;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace MVCGridDemo.Controllers  
  6. {  
  7.     public class SuperDogController : Controller  
  8.     {  
  9.         /// <summary>  
  10.         /// This method returns the list of dogs  
  11.         /// </summary>  
  12.         /// <returns></returns>  
  13.         public ActionResult Index()  
  14.         {  
  15.             var model = new SuperDogs();  
  16.             List<SuperDogs> dogGrid = model.GetHardCodedValues();  
  17.             return View(dogGrid);  
  18.         }  
  19.   
  20.        
  21.     }  
  22. }  
Our controller finally looks like the preceding code block. You can see the required using statements are bieng used here and are sorted alphabetically. The Green lines above the Action method Index are XML comment lines, that can be added by just typing "///" just above the action. Then we just need to add a description like this method does what.

Now let's discuss the codes inside the Action method.

The first line is the instantiation of the model class that we added. This we are instantiating since we need to access the collection of data objects that we have created inside the method GetHardCodedvalues().
Then we add and initialize the List of SuperDogs or the List of model classes that we will be using inside the view (IEnumerable<SuperDogs>) and set it to access the list method that returns a list of objects of type SuperDog that we have hardcoded. Then since the view expects an IEnumerable/List of the SuperDog model we return it into the view. Let's have a look at the view below:
  1. @model IEnumerable<MVCGridDemo.Models.SuperDogs>  
This is  the  model used in the view.

Now it's time to add the Grid code block into our view. The MVC Grid is used using:
  1. @using GridMvc.Html
  2. @Html.Grid(Model).Columns(columns =>columns.Add(c=>c.ID))  
The preceding using statement is required in the viewpage where the Grid would be used to make that accessible using HTML, like @Html.Grid(ModelName) with the column names/properties of the model. "@" is used in Razor syntax.

Finally the view with the html MVC Grid looks as in the following:
  1. @using GridMvc.Html  
  2. @model IEnumerable<MVCGridDemo.Models.SuperDogs>  
  3.   
  4. @{  
  5.     ViewBag.Title = "Index";  
  6. }  
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <link href="@Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />  
  11.     <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" />  
  12.     <script src="@Url.Content("~/Scripts/gridmvc.min.js")"></script>  
  13.     <title>Dog List</title>  
  14. </head>  
  15. <body>  
  16.     <h1>Dog List</h1>  
  17.     <hr />  
  18.     <div style="width:500px;">  
  19.         @Html.Grid(Model).Columns(columns =>  
  20.                     {  
  21.                         columns.Add(c => c.DogName).Titled("Dog Name");  
  22.                         columns.Add(c => c.BreedName).Titled("Breed").Filterable(true);  
  23.                         columns.Add(c => c.DogAge).Titled("Age");  
  24.                         columns.Add(c => c.DogOwner).Titled("Owner Name");  
  25.                     }).WithPaging(3).Sortable(true)  
  26.     </div>  
  27. </body>  
  28. </html>  
The functionalities like Sortable() accept a boolean value WithPaging() the value parameter that suggests the number of records in the grid and the Titled() is used to add the title of the respective column. You can also see the reference for the StyleSheets(.css) and Scripts(.js) for the gridmvc and bootstrap too. Finally when we run the application using the URL : "/SuperDog/Index" and we get the following result:

The preceding is the final grid for the Page 1.

The preceding is the grid results for the Page 2.
 
Conclusion
This is a very simple article that shows the basic implementation and installation of the grid in MVC . We can also download the grid.MVC from the link: Codeplex Link .

In the next article or Part 2 I will show how to create  a record and dynamically get the records from the database and bind the Grid.

I hope this would help in creating the grid. You can also download the source code file. 


Similar Articles
Invincix Solutions Private limited
Every INVINCIAN will keep their feet grounded, to ensure, your head is in the cloud