Starting SQL Server
Create a table as in the following:
- CREATE TABLE [dbo].[Product](
- [pid] [bigint] IDENTITY(1,1) Primary Key NOT NULL,
- [productID] [bigint] NULL,
- [Productname] [varchar](20) NULL,
- [Productprice] [varchar](20) NULL,
- [ProductDate] [datetime] NULL,
- [ProductGrade] [char](1) NULL,
- [ProductMfg] [varchar](50) NULL
- )
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:
- public class modeldata
- {
- public Int64 pid { get; set; }
- public Int64 productID { get; set; }
- public string Productname { get; set; }
- public string Productprice { get; set; }
- public DateTime ProductDate { get; set; }
- public char ProductGrade { get; set; }
- public string ProductMfg { get; set; }
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using Gridsample.Models;
- namespace Gridsample.Connection
- {
- public class Connection
- {
- public DataSet mydata()
- {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
- SqlCommand cmd = new SqlCommand("select * from Product", con);
- cmd.CommandType = CommandType.Text;
- SqlDataAdapter da = new SqlDataAdapter();
- da.SelectCommand = cmd;
- DataSet myrec = new DataSet();
- da.Fill(myrec);
- return myrec;
- }
- }
- }
After retrieving data we have just completed the work on the database.
Now we will work with the Controller and View.
ControllerInside 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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Data;
- using Gridsample.Models;
- namespace Gridsample.Controllers
- {
- public class GridviewController : Controller
- {
- public ActionResult grid()
- {
- List<modeldata> lmd = new List<modeldata>();
- DataSet ds = new DataSet();
- Connection.Connection con = new Connection.Connection();
- ds = con.mydata();
- foreach (DataRow dr in ds.Tables[0].Rows)
- {
- lmd.Add(new modeldata
- {
- pid = Convert.ToInt64(dr["pid"]),
- productID = Convert.ToInt64(dr["productID"]),
- Productname = dr["Productname"].ToString(),
- Productprice = dr["Productprice"].ToString(),
- ProductDate = Convert.ToDateTime(dr["ProductDate"]),
- ProductGrade = (char)dr["ProductGrade"],
- ProductMfg = dr["ProductMfg"].ToString()
- });
- }
- return View(lmd);
- }
- }
- }
ViewAfter 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.
- @model IEnumerable<Gridsample.Models.modeldata>
- @{
- ViewBag.Title = "grid";
- }
- <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.
- @{
- ViewBag.Title = "grid";
- WebGrid grid = new WebGrid(Model, rowsPerPage: 5);
- }
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.
- @model IEnumerable<Gridsample.Models.modeldata>
- @{
- ViewBag.Title = "grid";
- WebGrid grid = new WebGrid(Model, rowsPerPage: 5);
- }
- <h2>Grid</h2>
- <style type="text/css">
- .table
- {
- margin: 4px;
- border-collapse: collapse;
- width: 300px;
- }
- .header
- {
- background-color: gray;
- font-weight: bold;
- color: #fff;
- }
- .table th, .table td
- {
- border: 1px solid black;
- padding: 5px;
- }
- </style>
- @grid.GetHtml(
- tableStyle: "table", // applying style on grid
- fillEmptyRows: true,
- //show empty row when there is only one record on page to it will display all empty rows there.
- headerStyle: "header", //applying style.
- footerStyle: "grid-footer", //applying style.
- mode: WebGridPagerModes.All, //paging to grid
- firstText: "<< First",
- previousText: "< Prev",
- nextText: "Next >",
- lastText: "Last >>",
- columns: new[] // colums in grid
- {
- grid.Column("productID"), //the model fields to display
- grid.Column("Productname" ),
- grid.Column("Productprice"),
- grid.Column("ProductDate"),
- grid.Column("ProductGrade"),
- grid.Column("ProductMfg"),
- })
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.
Harsha KammarPosted Aug 13, 2021, 5:48 AM
In View page i am unable to use WebGrid, Any particular package needs to be installed?
Raghuram PerlaPosted May 26, 2020, 11:25 AM
By using this approach on click of page number it is again hitting controller action method and unnecessarily retrieving the results. How to avoid this issue.
Dinesh GabhanePosted Nov 12, 2019, 6:42 AM
Nice article Sir. Thanks
Bhavesh JadavPosted Mar 14, 2019, 1:26 PM
Nice article Sir....
Balamurugan APosted Dec 7, 2017, 9:02 AM
This is a nice tutorial. I was able to implement this in my project using the sample code with relative ease.
Ramesh PalanivelPosted Sep 20, 2017, 11:11 PM
nice Article sir...
vasu devanPosted Sep 20, 2017, 9:36 AM
How will you show varbinary from database to grid?
Azam SunasaraPosted Sep 15, 2017, 6:53 AM
Something update i want to gridview in default one rows and save then an add gridview in thoese added data is this possible thnks in advance please help me
jagadeesh BollabathiniPosted Jan 10, 2017, 6:13 AM
This article saved a lot of effort. Thank you.
Daniel OramPosted Oct 2, 2016, 6:53 PM
This is a great tutorial! I was able to implement this in my project using the sample code with relative ease. Thank you so much!
Chetan JogiPosted Feb 20, 2016, 2:58 AM
how to call data using ajax
Saineshwar BageriPosted Jan 26, 2016, 7:33 AM
i am showing data from database on grid
Amit ThankiPosted Jan 26, 2016, 7:02 AM
how to insert data in web grid in mvc 4 razor without Using Entity framework
Rajashekar KPosted Oct 8, 2015, 6:35 AM
thnks sir i got it
Hardip RPosted Sep 3, 2015, 3:12 AM
how to perform edit by adding link button....
harshil gandhiPosted Aug 27, 2015, 8:20 AM
Thank u sir @@Saineshwar Bageri..
harshil gandhiPosted Aug 27, 2015, 8:20 AM
@Saineshwar Bageri..... I solved the problem..... The problem was in Layout.cshtml page.... after loading the grid page....the layout page is loaded ...in the layout page...i wrote the @model without iennumerable.....
DarinPosted Aug 27, 2015, 8:18 AM
Thanks for the code, dude.......... Its working !!
harshil gandhiPosted Aug 27, 2015, 6:25 AM
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mvc4App3.Models.Emp]', but this dictionary requires a model item of type 'Mvc4App3.Models.Emp'.
ramesh saladiPosted Jul 29, 2015, 8:42 AM
can u send me and nice pdf r book name to learn mvc clearly
ramesh saladiPosted Jul 29, 2015, 8:37 AM
thank you
Hemanth KumarPosted Jun 17, 2015, 6:55 AM
My Dear it was very simple , but getting some casting issue in the controller while adding datarow to the list....
suyash salunkhePosted Jun 1, 2015, 6:40 AM
Bhai ye b batana chahiye na k how to add webgrid..Giving error 'WebGrid' could not be found (are you missing a using directive or an assembly reference?)
shobia therasaPosted May 8, 2015, 7:10 AM
Thank u sir it work for me.., u gave a simple code which satisfy my needs thank u so much.., u help me a lot...
shobia therasaPosted May 8, 2015, 7:09 AM
Thank u sir i work for me.., u gave a simple code which satisfy my needs thank u so much.., u help me a lot...
Saineshwar BageriPosted Feb 27, 2015, 10:56 PM
it should work
Beto PastranaPosted Feb 27, 2015, 9:46 AM
Visual Studio 2012
Saineshwar BageriPosted Feb 27, 2015, 12:03 AM
Beto Pastrana sir which visual studio you are using
Beto PastranaPosted Feb 26, 2015, 3:26 PM
A data source must be bound before this operation can be performed [InvalidOperationException: A data source must be bound before this operation can be performed.] System.Web.Helpers.WebGrid.EnsureDataBound() +69364 System.Web.Helpers.WebGrid.get_PageCount() +28 System.Web.Helpers.WebGrid.GetHtml(String tableStyle, String headerStyle, String footerStyle, String rowStyle, String alternatingRowStyle, String selectedRowStyle, String caption, Boolean displayHeader, Boolean fillEmptyRows, String emptyRowCellValue, IEnumerable`1 columns, IEnumerable`1 exclusions, WebGridPagerModes mode, String firstText, String previousText, String nextText, String lastText, Int32 numericLinksCount, Object htmlAttributes) +104 ASP._Page_Views_Home_grid_cshtml.Execute() in h:\Visual Studio 2012\Projects\Emergency Room Services System\ERSS.Web\Views\Home\grid.cshtml:30 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +96 System.Web.WebPages.StartPage.RunPage() +17 System.Web.WebPages.StartPage.ExecutePageHierarchy() +62 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +259 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +294 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +175 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Beto PastranaPosted Feb 26, 2015, 3:25 PM
Hi, Sorry but after downloading the code and following it, I'm getting next error:
prem kumarPosted Oct 14, 2014, 7:24 AM
would you tell how to step by step to develop mvc application.....
prem kumarPosted Oct 14, 2014, 7:22 AM
sir am new to mvc would you tell create model and class with two data's because am new to mvc
Ankita DengarePosted Sep 18, 2014, 2:58 AM
Thank you sir...
Ankita DengarePosted Aug 26, 2014, 9:00 AM
hello sir some error like this is occured System.InvalidCastException: Specified cast is not valid. in GridView controller when new add lmd to new ModelData... Please give me Solution for this...