Creating Simple WebGrid In MVC 4 Using Simple Model And Dataset

Starting SQL Server

Create a table as in the following:

  1. CREATE TABLE [dbo].[Product](  
  2. [pid] [bigint] IDENTITY(1,1) Primary Key NOT NULL,  
  3. [productID] [bigintNULL,  
  4. [Productname] [varchar](20) NULL,  
  5. [Productprice] [varchar](20) NULL,  
  6. [ProductDate] [datetime] NULL,  
  7. [ProductGrade] [char](1) NULL,  
  8. [ProductMfg] [varchar](50) NULL  
  9. )  

Table View



Display Records



Code part

In Solution Explorer, right-click the Controllers folder and then select Add Controller and name it GridviewController.



After adding a Controller I am just adding a Model and naming it modeldata.

To add a model right-click on the Model folder and then select Add Model.



Inside modeldata.cs we will set properties for get and set as in the following:

  1. public class modeldata  
  2. {  
  3.    public Int64 pid { getset; }  
  4.    public Int64 productID { getset; }  
  5.    public string Productname { getset; }  
  6.    public string Productprice { getset; }  
  7.    public DateTime ProductDate { getset; }  
  8.    public char ProductGrade { getset; }  
  9.    public string ProductMfg { getset; }  
  10. }  
After adding the Model I will add a connection class.

Because I am not using the Entity Framework (EF) I need to manually write code to retrieve data from the database.

For this I have added a folder and named it Connection.



Inside that folder I added a Connection.cs file for the Connection class as in the following:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8. using Gridsample.Models;  
  9. namespace Gridsample.Connection  
  10. {  
  11.     public class Connection  
  12.     {  
  13.         public DataSet mydata()  
  14.         {  
  15.             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());  
  16.             SqlCommand cmd = new SqlCommand("select * from Product", con);  
  17.             cmd.CommandType = CommandType.Text;  
  18.             SqlDataAdapter da = new SqlDataAdapter();  
  19.             da.SelectCommand = cmd;  
  20.             DataSet myrec = new DataSet();  
  21.             da.Fill(myrec);  
  22.             return myrec;  
  23.         }  
  24.     }  
  25. }  

After retrieving data we have just completed the work on the database.

Now we will work with the Controller and View.

Controller

Inside the controller I am just getting data from the Connection class and adding it to the dataset.

Then I have created a List of Model List<Modeldata>.

And adding dataset rows into the list.

And returning the View with the Model.

View(lmd);

Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Data;  
  7. using Gridsample.Models;  
  8. namespace Gridsample.Controllers  
  9. {  
  10.     public class GridviewController : Controller  
  11.     {  
  12.         public ActionResult grid()  
  13.         {  
  14.             List<modeldata> lmd = new List<modeldata>();  // creating list of model.  
  15.             DataSet ds = new DataSet();  
  16.             Connection.Connection con = new Connection.Connection(); // connection to getdata.  
  17.             ds = con.mydata(); // fill dataset  
  18.             foreach (DataRow dr in ds.Tables[0].Rows) // loop for adding add from dataset to list<modeldata>  
  19.             {  
  20.                 lmd.Add(new modeldata  
  21.                 {  
  22.                     pid = Convert.ToInt64(dr["pid"]), // adding data from dataset row in to list<modeldata>  
  23.                     productID = Convert.ToInt64(dr["productID"]),  
  24.                     Productname = dr["Productname"].ToString(),  
  25.                     Productprice = dr["Productprice"].ToString(),  
  26.                     ProductDate = Convert.ToDateTime(dr["ProductDate"]),  
  27.                     ProductGrade = (char)dr["ProductGrade"],  
  28.                     ProductMfg = dr["ProductMfg"].ToString()  
  29.                 });  
  30.             }  
  31.             return View(lmd);  
  32.         }  
  33.     }  
  34. }  
View

After doing the controller now to do the View.

Right-click on the Action result (grid) and select Add View.

While adding the view we will create a strongly-typed view.

And in the model class select the name of the model that we created (modeldata).

In the Scaffold template select List.



After adding, it will create a Grid for you, just delete the complete code from the table and keep the Header part.

  1. @model IEnumerable<Gridsample.Models.modeldata>  
  2. @{  
  3.     ViewBag.Title = "grid";  
  4. }  
  5. <h2>grid</h2>



The preceding shows the result of deleting the unwanted stuff.

Just access the webgrid class and create an object of WebGrid and pass a model to it.

  1. @{  
  2.     ViewBag.Title = "grid";  
  3.     WebGrid grid = new WebGrid(Model, rowsPerPage: 5);  
  4. }  

You must be thinking, what is a rowperpage?

It is a property of WebGrid to display a number of rows per page in a grid.



After creating an object just create a grid from it.
  1. @model IEnumerable<Gridsample.Models.modeldata>  
  2. @{  
  3.     ViewBag.Title = "grid";  
  4.     WebGrid grid = new WebGrid(Model, rowsPerPage: 5);  
  5. }  
  6. <h2>Grid</h2>  
  7.     <style type="text/css">  
  8.         .table  
  9.         {  
  10.             margin4px;  
  11.             border-collapsecollapse;  
  12.             width300px;  
  13.         }  
  14.         .header  
  15.         {  
  16.             background-colorgray;  
  17.             font-weightbold;  
  18.             color#fff;  
  19.         }  
  20.         .table th, .table td  
  21.         {  
  22.             border1px solid black;  
  23.             padding5px;  
  24.         }  
  25.     </style>  
  26. @grid.GetHtml(  
  27.     tableStyle: "table", // applying style on grid  
  28.     fillEmptyRows: true,   
  29.     //show empty row when there is only one record on page to it will display all empty rows there.  
  30.     headerStyle: "header", //applying style.  
  31.     footerStyle: "grid-footer", //applying style.  
  32.     mode: WebGridPagerModes.All, //paging to grid   
  33.     firstText: "<< First",  
  34.     previousText: "< Prev",  
  35.     nextText: "Next >",  
  36.     lastText: "Last >>",  
  37.     columns: new[]  // colums in grid  
  38.     {  
  39.         grid.Column("productID"), //the model fields to display  
  40.         grid.Column("Productname"  ),  
  41.         grid.Column("Productprice"),  
  42.         grid.Column("ProductDate"),  
  43.         grid.Column("ProductGrade"),  
  44.         grid.Column("ProductMfg"),  
  45.    })  
After this just run your application and its done.

Final Output



One thing remaining to explain is empty rows.

The answer is as in the following:
 
fillEmptyRows: true, 

Show an empty row when there is only one record on the page so it will display all empty rows there.

If you do not understand then just download the code and check the flow, you will understand.



Simple code for a webgrid in MVC. You can check all of the example and compare.


Similar Articles