Creating Simple WebGrid In MVC 4 Using Simple Model And Dataset

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 { getset; }

   public Int64 productID { getset; }

   public string Productname { getset; }

   public string Productprice { getset; }

   public DateTime ProductDate { getset; }

   public char ProductGrade { getset; }

   public string ProductMfg { getset; }

}


After adding the Model I will add a connection class.

Because I am not use the Entity Framwork (EF) I need to manully write code to retreive 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.

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 returing 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>();  // creating list of model.

 

            DataSet ds = new DataSet();

 

            Connection.Connection con = new Connection.Connection(); // connection to getdata.

 

            ds = con.mydata(); // fill dataset

 

            foreach (DataRow dr in ds.Tables[0].Rows) // loop for adding add from dataset to list<modeldata>

            {

                lmd.Add(new modeldata

                {

                    pid = Convert.ToInt64(dr["pid"]), // adding data from dataset row in to list<modeldata>

                    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);

 

        }

 

    }

}


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.

@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?

Its 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

        {

            margin4px;

            border-collapsecollapse;

            width300px;

        }

        .header

        {

            background-colorgray;

            font-weightbold;

            color#fff;

        }

        .table th.table td

        {

            border1px solid black;

            padding5px;

        }

    </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.