Display Colorized Rows Or Cells Of WebGrid In ASP.NET MVC

Some custom requirements of clients are that cells or rows that are colored in red are pending, and those in green are completed. This helps them to know which one is pending and which one is completed. If you are new to MVC and don’t have knowledge about grids then have a look at the following articles:

  1. Creating-simple-webgrid-in-mvc-4-using-simple-model-and-data
  2. Filter-WebGrid-with-cascading-dropdown list-along-with-paging
  3. Load-on-demand-data-in-WebGrid-on-scroll-using-Asp-Net-MVC
Let’s start with creating a basic project in MVC.

Creating Application

Open Visual Studio IDE

From Visual Studio IDE Menus select File, New, then Project.

A New Project dialog will pop up from that. In the left panel select Templates and inside that select Visual C#, then Web. After that in Center Panel you will see List of ASP.NET Templates from that we are going to select “ASP.NET MVC 4 Web Application.” After selecting, just name your Project as “DEMO_WEBGRID” and finally click on the OK button to create project.

Template
                                                               Figure 1: Selecting Template

Project
                                    Figure 2: Selecting MVC 4 Project

After selecting all options as told above now click the OK button and your project will be created.

Project structure after adding.

structure
            Figure 3: Project structure

After creating project now let’s add a simple model.

Adding Model (OrderModel)

For adding model in solution explore, just right click on Model folder and select Add then inside that select Class and then Name class as OrderModel and finally click on Add button to create Model.

OrderModel
              Figure 4: Adding OrderModel

Adding Property to (OrderModel) Model, After adding model lets us add property to this model.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcApplication6.Models  
  7. {  
  8.     public class OrderModel   
  9.     {  
  10.         public int OrderID   
  11.       {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string OrderName   
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public string OrderType  
  21.         {  
  22.             get;  
  23.             set;  
  24.         }  
  25.     
  26.         public int OrderPrice   
  27.         {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string PaymentStatus  
  32.         {  
  33.             get;  
  34.             set;  
  35.         }  
  36.     }  
  37. }  
Adding (Home) Controller

To add controller just right click on Controllers folder then select Add from list and inside that select controller.

Controller
                                                               Figure 5: Adding Controller (Home Controller)

After selecting controller, a new dialog will pop up with the name Add Controller.

add

In the template we are going to select Empty MVC controller. Finally click on Add button to create HomeController.

After adding HomeController you will see Index Action Method created by default.

I am going to rename Index action Method to DisplayGrid.

Inside DisplayGrid action method I am going to create a List of (List<OrderModel>) and then going to add OrderModel. In this List we are going to display this data on grid. If you want you can replace this entire list and get data from the database and display in grid.

HomeController code snippet

Code snippet of HomeController with DisplayGrid Action Method.
  1. using DEMO_WEBGRID.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace DEMO_WEBGRID.Controllers  
  9. {  
  10.     public class HomeController: Controller  
  11.     {  
  12.         public ActionResult DisplayGrid()  
  13.         {  
  14.             List < OrderModel > LW = new List < OrderModel > ()  
  15.             {  
  16.                 new OrderModel  
  17.                 {  
  18.                     OrderID = 1,  
  19.                         OrderName = "Rice Plate Full",  
  20.                         OrderPrice = 500,  
  21.                         OrderType = "Hotel",  
  22.                         PaymentStatus = "Done"  
  23.                 },  
  24.                 new OrderModel   
  25.                 {  
  26.                     OrderID = 2,  
  27.                         OrderName = "Masala dosa",  
  28.                         OrderPrice = 300,  
  29.                         OrderType = "Online",  
  30.                         PaymentStatus = "Pending"  
  31.                 },  
  32.                 new OrderModel  
  33.                 {  
  34.                     OrderID = 3,  
  35.                         OrderName = "Pav bhaji masala",  
  36.                         OrderPrice = 300,  
  37.                         OrderType = "Online",  
  38.                         PaymentStatus = "Done"  
  39.                 },  
  40.                 new OrderModel  
  41.                 {  
  42.                     OrderID = 4,  
  43.                         OrderName = "Straw Berry shake",  
  44.                         OrderPrice = 200,  
  45.                         OrderType = "Online",  
  46.                         PaymentStatus = "Pending"  
  47.                 }  
  48.             };  
  49.             return View(LW);  
  50.         }  
  51.     }  
  52. }  
After displaying code snippet now let’s add View to DisplayGrid Action Method.

Adding View for DisplayGrid Action Method

For adding View just right click inside Action Method and then select Add View from List that pop ups.

view

add
                        Figure 6:
Adding DisplayGrid View

In this dialog of Add view we are not going on to select any Model because we are going to manually add it. After creating View the name of View will be the same as that of Action Method. After doing the required things now let’s click on add to Add a View.

This view will be added inthe Views folder; inside that there will be a folder with the name of your Controller and all views related to that controller will be kept inside that.

view
Figure 7: After adding DisplayGrid View

Now we havea  simple layout with some html tags.

tags

Now let’s add Model to this View.

Adding OrderModel to DisplayGrid View

We are going to add List of Order Model to View because we are going to display all this data in WebGrid.

@model List<DEMO_WEBGRID.Models.OrderModel>

After adding Model reference to View now we are going to add a WebGrid to this view to display data.

I have used a simple web grid and added a column which I want to display. And also I have given Id to this grid with the name “gridMapping”.

Code snippet of WebGrid
  1. @ {  
  2.     var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  3.     grid.Pager(WebGridPagerModes.All);  
  4. }  
  5.   
  6. @grid.GetHtml(  
  7.     htmlAttributes: new   
  8.     {  
  9.         id = "gridMapping"  
  10.     },  
  11.     tableStyle: "table table-bordered",  
  12.     headerStyle: "info",  
  13.     footerStyle: "webgrid-footer",  
  14.     alternatingRowStyle: "webgrid-alternating-row",  
  15.     selectedRowStyle: "webgrid-selected-row",  
  16.     rowStyle: "gridrow",  
  17.     columns: grid.Columns(  
  18.         grid.Column("OrderID""OrderID"),  
  19.         grid.Column("OrderName""Order Name"),  
  20.         grid.Column("OrderType""Type"),  
  21.         grid.Column("OrderPrice""Price"),  
  22.         grid.Column("PaymentStatus""Payment Status")  
  23.     )  
  24. )  
Now after adding this grid to View complete code snippet.

Code snippet of complete DisplayGrid view
  1. @model List < DEMO_WEBGRID.Models.OrderModel >  
  2.     @ {  
  3.         Layout = null;  
  4.     } < !DOCTYPE html >  
  5.   
  6.     < html >  
  7.     < head >  
  8.     < meta name = "viewport"  
  9. content = "width=device-width" / >  
  10.     < title > DisplayGrid < /title> < /head> < body >  
  11.     < div >  
  12.     @ {  
  13.         var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  14.         grid.Pager(WebGridPagerModes.All);  
  15.     }  
  16.   
  17.   
  18. @grid.GetHtml(  
  19.     htmlAttributes: new  
  20.     {  
  21.         id = "gridMapping"  
  22.     },  
  23.     tableStyle: "table table-bordered",  
  24.     headerStyle: "info",  
  25.     footerStyle: "webgrid-footer",  
  26.     alternatingRowStyle: "webgrid-alternating-row",  
  27.     selectedRowStyle: "webgrid-selected-row",  
  28.     rowStyle: "gridrow",  
  29.     columns: grid.Columns(  
  30.         grid.Column("OrderID""OrderID"),  
  31.         grid.Column("OrderName""Order Name"),  
  32.         grid.Column("OrderType""Type"),  
  33.         grid.Column("OrderPrice""Price"),  
  34.         grid.Column("PaymentStatus""Payment Status")  
  35.     )  
  36. ) < /div> < /body> < /html>  
Save and Run Application to see changes

Now save your application and run.

To Access this View enter URL.

e.g. #### is your Port number on which IIS is running.

Some Error of WebGrid if it is not Added or Reference

After running some people may finda compile time error.

Compiler Error Message: CS0246: The type or namespace name 'WebGrid' could not be found. (Are you missing a using directive or an assembly reference?)

error
                                                     Figure 8: Compile time error.

To resolve this error just Add Reference of [System.Web.Helpers.dll, v2.0.0.0] to your project.

Adding Reference of Web Helpers 2.0 to Project

To add Reference just right click on Reference tab in project and select Add Reference from list.

Reference
                                  Figure 9: Add Reference.

After that a new dialog of Reference Manager will pop up from that, just select Extensions Menu from left panel.

And then find [System.Web.Helpers.dll, v2.0.0.0] i the list and check it and click on OK button.

refrences

Still some people might get an error. To resolve this you need to right click on [System.Web.Helpers] in reference tab and then Select Properties from the list, and in Properties there is an option named Copy Local. Just change it from False to True.

properties

Save and Run Application to see changes

After doing these changes now save your application and run project.

And access URL.

DisplayGrid
                                         Figure 10: Simple DisplayGrid View.

Downloading and adding script and css of Bootstrap to project.

A simple WebGrid is displayed.

Now we  have a question that it's a simple grid without any css; for adding .css we are going to use Bootstrap.

I have downloaded Bootstrap files from the site (http://getbootstrap.com/ ) and added a folder to your project.

Link to download Bootstrap.

folder
     Figure 11: After adding Bootstrap folder.

Adding Script and .css Reference to DisplayGrid View.

After adding Bootstrap now I am going to add .css and scripts of Bootstrap to format WebGrid.
  1. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  2.   
  3. <script src="~/Scripts/jquery-1.9.1.js"></script>  
  4. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  5. <style type="text/css">  
  6.     .mainpanel  
  7.     {  
  8.         margin-left: 230px;  
  9.         min-height: 636px;  
  10.         padding: 20px;  
  11.         padding-top: 20px;  
  12.         padding-right: 20px;  
  13.         padding-bottom: 20px;  
  14.         padding-left: 20px;  
  15.     }  
  16.       
  17.     .info th   
  18.     {  
  19.         background: #E0E0E0 !important;  
  20.     }  
  21.       
  22.     .info th a   
  23.     {  
  24.         color: #000000;  
  25.         font-weight: normal;  
  26.     }  
  27. </style>  
After adding script and css now save your application and run project.

Save and Run Application to see changes

And access URL

Grid is looking better than before.

WebGrid
                                             Figure 12: After adding bootstrap .css to WebGrid.

After formatting I have a condition that in a column where I have Payment Status, according to its payment status, I want to display the color in the grid column.

e.g.
  1. if(text == “Done”)  
  2. {  
  3.     Color = ”green”;  
  4. }  
  5. else  
  6. {  
  7.     Color = ”Red”;  
  8. }  
For doing this I have used JQuery.

In the following script onthe loading of the page I am going to check what the current value is inthe  5th column of the grid and according to that I will apply color to that column. If it is [Done], then Green and if [Pending], then it will be Red.

Displaying Column colored on base of condition
  1. <script type="text/javascript">  
  2.     $(document).ready(function()   
  3.       {  
  4.   
  5.         $('#gridMapping > tbody > tr').each(function(index)  
  6.         {  
  7.   
  8.             if ($(this).children('td:nth-child(5)').text() == "Done")  
  9.             {  
  10.                 $(this).children('td:nth-child(5)').css("background-color""#33CC99");  
  11.             } else  
  12.             {  
  13.                 $(this).children('td:nth-child(5)').css("background-color""#FFCC99");  
  14.             }  
  15.   
  16.         });  
  17.     });  
  18. </script>  
In the script first we are finding grid [gridMapping], then inside that we are finding [tbody], then finally [tr] on this tr we are applying loop and then inside this function we are going to check the text of Payment Status [$(this).children('td:nth-child(5)').text() == "Done")]. According to that we are going to apply .css to it.

After adding the above script to DisplayGrid View just save your application and run project.

webgrid
                                             Figure 13: After adding color to column in WebGrid.

Final view after applying color to column in Grid; if you want color on the basis of some other parameter then you do it.

After coloring this column, if some other requirement -- such as the user wants the entire row to be colore -- then see the following script.

Displaying entire row colored on base of condition
  1. <script type="text/javascript">  
  2.     $(document).ready(function()  
  3.        {  
  4.   
  5.         $('#gridMapping > tbody > tr').each(function(index)  
  6.             {  
  7.   
  8.             if ($(this).children('td:nth-child(5)').text() == "Done")  
  9.             {  
  10.                 $(this).children('td').css("background-color""#33CC99");  
  11.             } else   
  12.             {  
  13.                 $(this).children('td').css("background-color""#FFCC99");  
  14.             }  
  15.   
  16.         });  
  17.     });  
  18. </script>  

WebGrid
                                            Figure 14: After adding color to Entire Row in WebGrid.

Displaying the entire row color change on mouse hover. Add simple css in page header and simply do mouse over and have fun.
  1. <style type="text/css">  
  2.     #gridMapping tr:hover  
  3.     {  
  4.         background-color: #F5DEB3;  
  5.     }  
  6. </style>  
WebGrid
                                        Figure 15: Displaying color on mouse hover on Row WebGrid.

Code snippet of DisplayGrid View
  1. @model List < DEMO_WEBGRID.Models.OrderModel >  
  2.     @ {  
  3.         Layout = null;  
  4.     } < !DOCTYPE html >  
  5.   
  6.     < html >  
  7.     < head >  
  8.     < meta name = "viewport"  
  9. content = "width=device-width" / >  
  10.     < title > DisplayGrid < /title>  
  11.   
  12. < link href = "~/bootstrap-3.3.6-dist/css/bootstrap.min.css"  
  13. rel = "stylesheet" / >  
  14.   
  15.     < script src = "~/Scripts/jquery-1.9.1.js" > < /script> < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script>  
  16.   
  17. < style type = "text/css" >  
  18.     .mainpanel  
  19.     {  
  20.         margin - left: 230 px;  
  21.         min - height: 636 px;  
  22.         padding: 20 px;  
  23.         padding - top: 20 px;  
  24.         padding - right: 20 px;  
  25.         padding - bottom: 20 px;  
  26.         padding - left: 20 px;  
  27.     }  
  28.   
  29. .info th   
  30. {  
  31.     background: #E0E0E0!important;  
  32. }  
  33.   
  34. .info th a   
  35. {  
  36.     color: #000000;  
  37. font-weight: normal;  
  38. }  
  39. </style>  
  40.   
  41. <script type= "text/javascript" > /* coloring only single Cell*/  
  42.         $(document).ready(function() {  
  43.             debugger;  
  44.             $('#gridMapping > tbody > tr').each(function(index) {  
  45.   
  46.                 if ($(this).children('td:nth-child(5)').text() == "Done")  
  47.                 {  
  48.                     $(this).children('td:nth-child(5)').css("background-color""#33CC99");  
  49.                 } else  
  50.                 {  
  51.                     $(this).children('td:nth-child(5)').css("background-color""#FFCC99");  
  52.                 }  
  53.   
  54.             });  
  55.         }); < /script>  
  56.   
  57.     < script type = "text/javascript" > /* coloring entire Row */  
  58.     $(document).ready(function()  
  59.         {  
  60.         debugger;  
  61.         $('#gridMapping > tbody > tr').each(function(index)   
  62.            {  
  63.   
  64.             if ($(this).children('td:nth-child(5)').text() == "Done")  
  65.             {  
  66.                 $(this).children('td').css("background-color""#33CC99");  
  67.             } else   
  68.             {  
  69.                 $(this).children('td').css("background-color""#FFCC99");  
  70.             }  
  71.   
  72.         });  
  73.     }); < /script>  
  74.   
  75.   
  76.     < style type = "text/css" >  
  77.     /*Mouse hover*/  
  78.     #gridMapping tr: hover  
  79.     {  
  80.         background - color: #F5DEB3;  
  81.     } < /style>  
  82.   
  83.         < /head> < body >  
  84.         < div >  
  85.         @ {  
  86.             var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  87.             grid.Pager(WebGridPagerModes.All);  
  88.         }  
  89.   
  90.   
  91.         @grid.GetHtml(  
  92.         htmlAttributes: new   
  93.           {  
  94.             id = "gridMapping"  
  95.         },  
  96.         tableStyle: "table table-bordered",  
  97.         headerStyle: "info",  
  98.         footerStyle: "webgrid-footer",  
  99.         alternatingRowStyle: "webgrid-alternating-row",  
  100.         selectedRowStyle: "webgrid-selected-row",  
  101.         rowStyle: "gridrow",  
  102.         columns: grid.Columns(  
  103.             grid.Column("OrderID""OrderID"),  
  104.             grid.Column("OrderName""Order Name"),  
  105.             grid.Column("OrderType""Type"),  
  106.             grid.Column("OrderPrice""Price"),  
  107.             grid.Column("PaymentStatus""Payment Status")  
  108.         )  
  109.     ) < /div> < /body> < /html>  
In this tutorial we have completed coloring cells in WebGrid, coloring rows in WebGrid and finally mouse over color change of row.
I hope you have liked my tutorial.

Up Next
    Ebook Download
    View all
    Learn
    View all