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. namespace MvcApplication6.Models
  6. {
  7. public class OrderModel
  8. {
  9. public int OrderID
  10. {
  11. get;
  12. set;
  13. }
  14. public string OrderName
  15. {
  16. get;
  17. set;
  18. }
  19. public string OrderType
  20. {
  21. get;
  22. set;
  23. }
  24. public int OrderPrice
  25. {
  26. get;
  27. set;
  28. }
  29. public string PaymentStatus
  30. {
  31. get;
  32. set;
  33. }
  34. }
  35. }
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. namespace DEMO_WEBGRID.Controllers
  8. {
  9. public class HomeController: Controller
  10. {
  11. public ActionResult DisplayGrid()
  12. {
  13. List < OrderModel > LW = new List < OrderModel > ()
  14. {
  15. new OrderModel
  16. {
  17. OrderID = 1,
  18. OrderName = "Rice Plate Full",
  19. OrderPrice = 500,
  20. OrderType = "Hotel",
  21. PaymentStatus = "Done"
  22. },
  23. new OrderModel
  24. {
  25. OrderID = 2,
  26. OrderName = "Masala dosa",
  27. OrderPrice = 300,
  28. OrderType = "Online",
  29. PaymentStatus = "Pending"
  30. },
  31. new OrderModel
  32. {
  33. OrderID = 3,
  34. OrderName = "Pav bhaji masala",
  35. OrderPrice = 300,
  36. OrderType = "Online",
  37. PaymentStatus = "Done"
  38. },
  39. new OrderModel
  40. {
  41. OrderID = 4,
  42. OrderName = "Straw Berry shake",
  43. OrderPrice = 200,
  44. OrderType = "Online",
  45. PaymentStatus = "Pending"
  46. }
  47. };
  48. return View(LW);
  49. }
  50. }
  51. }
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. @grid.GetHtml(
  6. htmlAttributes: new
  7. {
  8. id = "gridMapping"
  9. },
  10. tableStyle: "table table-bordered",
  11. headerStyle: "info",
  12. footerStyle: "webgrid-footer",
  13. alternatingRowStyle: "webgrid-alternating-row",
  14. selectedRowStyle: "webgrid-selected-row",
  15. rowStyle: "gridrow",
  16. columns: grid.Columns(
  17. grid.Column("OrderID", "OrderID"),
  18. grid.Column("OrderName", "Order Name"),
  19. grid.Column("OrderType", "Type"),
  20. grid.Column("OrderPrice", "Price"),
  21. grid.Column("PaymentStatus", "Payment Status")
  22. )
  23. )
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. < html >
  6. < head >
  7. < meta name = "viewport"
  8. content = "width=device-width" / >
  9. < title > DisplayGrid < /title> < /head> < body >
  10. < div >
  11. @ {
  12. var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);
  13. grid.Pager(WebGridPagerModes.All);
  14. }
  15. @grid.GetHtml(
  16. htmlAttributes: new
  17. {
  18. id = "gridMapping"
  19. },
  20. tableStyle: "table table-bordered",
  21. headerStyle: "info",
  22. footerStyle: "webgrid-footer",
  23. alternatingRowStyle: "webgrid-alternating-row",
  24. selectedRowStyle: "webgrid-selected-row",
  25. rowStyle: "gridrow",
  26. columns: grid.Columns(
  27. grid.Column("OrderID", "OrderID"),
  28. grid.Column("OrderName", "Order Name"),
  29. grid.Column("OrderType", "Type"),
  30. grid.Column("OrderPrice", "Price"),
  31. grid.Column("PaymentStatus", "Payment Status")
  32. )
  33. ) < /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. <script src="~/Scripts/jquery-1.9.1.js"></script>
  3. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
  4. <style type="text/css">
  5. .mainpanel
  6. {
  7. margin-left: 230px;
  8. min-height: 636px;
  9. padding: 20px;
  10. padding-top: 20px;
  11. padding-right: 20px;
  12. padding-bottom: 20px;
  13. padding-left: 20px;
  14. }
  15. .info th
  16. {
  17. background: #E0E0E0 !important;
  18. }
  19. .info th a
  20. {
  21. color: #000000;
  22. font-weight: normal;
  23. }
  24. </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. $('#gridMapping > tbody > tr').each(function(index)
  5. {
  6. if ($(this).children('td:nth-child(5)').text() == "Done")
  7. {
  8. $(this).children('td:nth-child(5)').css("background-color", "#33CC99");
  9. } else
  10. {
  11. $(this).children('td:nth-child(5)').css("background-color", "#FFCC99");
  12. }
  13. });
  14. });
  15. </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. $('#gridMapping > tbody > tr').each(function(index)
  5. {
  6. if ($(this).children('td:nth-child(5)').text() == "Done")
  7. {
  8. $(this).children('td').css("background-color", "#33CC99");
  9. } else
  10. {
  11. $(this).children('td').css("background-color", "#FFCC99");
  12. }
  13. });
  14. });
  15. </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. < html >
  6. < head >
  7. < meta name = "viewport"
  8. content = "width=device-width" / >
  9. < title > DisplayGrid < /title>
  10. < link href = "~/bootstrap-3.3.6-dist/css/bootstrap.min.css"
  11. rel = "stylesheet" / >
  12. < script src = "~/Scripts/jquery-1.9.1.js" > < /script> < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script>
  13. < style type = "text/css" >
  14. .mainpanel
  15. {
  16. margin - left: 230 px;
  17. min - height: 636 px;
  18. padding: 20 px;
  19. padding - top: 20 px;
  20. padding - right: 20 px;
  21. padding - bottom: 20 px;
  22. padding - left: 20 px;
  23. }
  24. .info th
  25. {
  26. background: #E0E0E0!important;
  27. }
  28. .info th a
  29. {
  30. color: #000000;
  31. font-weight: normal;
  32. }
  33. </style>
  34. <script type= "text/javascript" > /* coloring only single Cell*/
  35. $(document).ready(function() {
  36. debugger;
  37. $('#gridMapping > tbody > tr').each(function(index) {
  38. if ($(this).children('td:nth-child(5)').text() == "Done")
  39. {
  40. $(this).children('td:nth-child(5)').css("background-color", "#33CC99");
  41. } else
  42. {
  43. $(this).children('td:nth-child(5)').css("background-color", "#FFCC99");
  44. }
  45. });
  46. }); < /script>
  47. < script type = "text/javascript" > /* coloring entire Row */
  48. $(document).ready(function()
  49. {
  50. debugger;
  51. $('#gridMapping > tbody > tr').each(function(index)
  52. {
  53. if ($(this).children('td:nth-child(5)').text() == "Done")
  54. {
  55. $(this).children('td').css("background-color", "#33CC99");
  56. } else
  57. {
  58. $(this).children('td').css("background-color", "#FFCC99");
  59. }
  60. });
  61. }); < /script>
  62. < style type = "text/css" >
  63. /*Mouse hover*/
  64. #gridMapping tr: hover
  65. {
  66. background - color: #F5DEB3;
  67. } < /style>
  68. < /head> < body >
  69. < div >
  70. @ {
  71. var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);
  72. grid.Pager(WebGridPagerModes.All);
  73. }
  74. @grid.GetHtml(
  75. htmlAttributes: new
  76. {
  77. id = "gridMapping"
  78. },
  79. tableStyle: "table table-bordered",
  80. headerStyle: "info",
  81. footerStyle: "webgrid-footer",
  82. alternatingRowStyle: "webgrid-alternating-row",
  83. selectedRowStyle: "webgrid-selected-row",
  84. rowStyle: "gridrow",
  85. columns: grid.Columns(
  86. grid.Column("OrderID", "OrderID"),
  87. grid.Column("OrderName", "Order Name"),
  88. grid.Column("OrderType", "Type"),
  89. grid.Column("OrderPrice", "Price"),
  90. grid.Column("PaymentStatus", "Payment Status")
  91. )
  92. ) < /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.