Click here to Skip to main content
14,773,652 members
Articles » Web Development » ASP.NET » General
Posted 14 Jul 2013


72 bookmarked

WebGrid in ASP.NET MVC4

Rate me:
Please Sign up or sign in to vote.
4.79/5 (47 votes)
14 Jul 2013CPOL
This tip will help you to develop a webgrid in ASP.NET MVC application.


We can define WebGrid to display data on a web page using an HTML table element. It renders tabular data in a very simple manner with support for custom formatting of columns, paging, sorting, and asynchronous updates via AJAX.

The main properties in WebGrid are:

  • Source – Where your data comes from. Usually the model passed by the controller action.
  • DefaultSort – Here you can define how the data will be sorted. Just provide the column name here.
  • RowsPerPage – Number of records that will be shown on table.
  • CanPage – Allows paging.
  • CanSort – Allows sorting by clicking on column title.
  • SelectedFieldName - Gets full name of the query-string field that is used to specify the selected row of the WebGrid instance.

Using the Code

In this tip, I will explain how to use WebGrid in an ASP.NET MVC 4 application. First, I am going to create a Model named Product.


public class Product
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public long Quantity { get; set; }

I am using Razor view engine and my InventoryController contains the following action:


public ActionResult WebgridSample()
    ObservableCollection<Product> inventoryList = 
    	new ObservableCollection<Product>();
    inventoryList.Add(new Product { Id = "P101", 
    Name = "Computer", Description = "All type of computers", Quantity = 800 });
    inventoryList.Add(new Product { Id = "P102", 
    Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
    inventoryList.Add(new Product { Id = "P103", 
    Name = "Camera", Description = "Hd  cameras", Quantity = 300 });
    inventoryList.Add(new Product { Id = "P104", 
    Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
    inventoryList.Add(new Product { Id = "P105", 
    Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
    inventoryList.Add(new Product { Id = "P106", 
    Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
    inventoryList.Add(new Product { Id = "P107", 
    Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
    return View(inventoryList);

In my WebgridSample View, I am creating a WebGrid and specify the columns in the call to GetHtml.


    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, 
    selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");

The WebGrid helper allows us to add class names to style the table, header, footer, row, and alternating row elements.

<style type="text/css">
    .webGrid { margin: 4px; border-collapse: collapse; width: 500px;  background-color:#B4CFC3;}
    .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
    .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
    .alt { background-color: #E4E9F5; color: #000; }
    .gridHead a:hover {text-decoration:underline;}
    .description { width:auto}
    .select{background-color: #71857C}

Adding the columns to a grid for specifying the column order, name, and field to bind:

<div id="gridContent">
    @grid.GetHtml(tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            columns: grid.Columns(
            grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)),
            grid.Column("Name", " Name"),
            grid.Column("Description", "Description", style: "description"),
            grid.Column("Quantity", "Quantity")

For navigating the selected item, I use the format parameter in the Id column. The format parameter of the Column method allows us to customize the rendering of a data item.

grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)) 

The below code display the selected row in an HTML code block, and for that I created an instance of the model Product.

    InventoryManagement.Models.Product product = new InventoryManagement.Models.Product();

@if (grid.HasSelection)
 product = (InventoryManagement.Models.Product)grid.Rows[grid.SelectedIndex].Value;
 <b>Id</b> @product.Id<br />
 <b>Name</b>  @product.Name<br />
 <b>Description</b> @product.Description<br />
 <b>Quantity</b> @product.Quantity<br />

For avoiding page refresh while pagination, we can add an AJAX parameter ajaxUpdateContainerId and wrap the grid markup with a DIV element. Here we can assign the div id as  ajaxUpdateContainerId.

ajaxUpdateContainerId: "gridContent"

Add a reference to jQuery.

 <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>   

Image 1

Here in this  example if you want to get the selected item from webgrid and want to show in seperate page, yoy can use Action link in webgrid column.

@Html.ActionLink("Link text",
                         "Action Method Name",
                         "Controller Name",
                        "Route value",
grid.Column("Detail", format: @<text>@Html.ActionLink("Select", "Submit",
                new { QtId = item.QtId }) </text>),

In the Action , you can pass the parameter as id and retrieve the corresponding value to show in the page.


  • 4th July, 2013: Initial post.

This tip is based on this blog.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

India India
No Biography provided

Comments and Discussions

QuestionHelpful Post Pin
K K Srinivasan29-Sep-15 5:33
MemberK K Srinivasan29-Sep-15 5:33 
GeneralNice Article Pin
Member 1052774815-Jun-15 21:01
MemberMember 1052774815-Jun-15 21:01 
QuestionAbout edit template inside webgrid Pin
Member 1066626226-Jan-15 22:30
MemberMember 1066626226-Jan-15 22:30 
QuestionNice written a similiar one Pin
Shivprasad koirala20-Nov-14 2:56
MemberShivprasad koirala20-Nov-14 2:56 
QuestionExcellent Pin
krakoss@mail.ru24-Oct-14 3:42
professionalkrakoss@mail.ru24-Oct-14 3:42 
QuestionGood article Pin
jetendramanpradhan24-Jul-14 20:06
Memberjetendramanpradhan24-Jul-14 20:06 
Questionwhat is ObservableCollection Pin
Member 80204536-Jul-14 7:18
MemberMember 80204536-Jul-14 7:18 
AnswerRe: what is ObservableCollection Pin
krakoss@mail.ru24-Oct-14 3:40
professionalkrakoss@mail.ru24-Oct-14 3:40 
Questionweb grid in mvc 4 razor(.vbhtml) Pin
avelsamy27-Mar-14 21:54
Memberavelsamy27-Mar-14 21:54 
QuestionAdding Id value to a checkbox Pin
lherselman13-Mar-14 23:59
Memberlherselman13-Mar-14 23:59 
SuggestionOverall helpful Topic for WebGrid Pin
Monibrata Bhattacharjee11-Feb-14 19:47
MemberMonibrata Bhattacharjee11-Feb-14 19:47 
GeneralMy vote of 3 Pin
matheus-guimaraes10-Feb-14 12:38
Membermatheus-guimaraes10-Feb-14 12:38 
QuestionError on running Pin
joeller30-Jan-14 9:58
professionaljoeller30-Jan-14 9:58 
GeneralMy vote of 5 Pin
Member 1032399326-Jan-14 1:13
professionalMember 1032399326-Jan-14 1:13 
Questionradio button instead of select link Pin
olaleye_oladejo2-Dec-13 5:44
Memberolaleye_oladejo2-Dec-13 5:44 
QuestionQuerystring parameters not showing up in url after click!?! Pin
Luc Archambault22-Nov-13 21:13
MemberLuc Archambault22-Nov-13 21:13 
QuestionThe best overloaded method match for 'System.Web.Helpers.WebGridRow.GetSelectLink(string)' has some invalid arguments Pin
Tony Girgenti1-Oct-13 14:06
MemberTony Girgenti1-Oct-13 14:06 
AnswerRe: The best overloaded method match for 'System.Web.Helpers.WebGridRow.GetSelectLink(string)' has some invalid arguments Pin
indianDEV8-May-14 2:16
MemberindianDEV8-May-14 2:16 
GeneralMy vote of 5 Pin
Sampath Lokuge15-Jul-13 0:43
MemberSampath Lokuge15-Jul-13 0:43 
GeneralMy vote of 4 Pin
Deenuji11-Jul-13 22:37
MemberDeenuji11-Jul-13 22:37 
Questionhow do i add button i each column Pin
vidhya511-Jul-13 1:19
Membervidhya511-Jul-13 1:19 
AnswerRe: how do i add button i each column Pin
josh-jw11-Jul-13 19:07
Memberjosh-jw11-Jul-13 19:07 
GeneralMy vote of 5 Pin
GregoryW8-Jul-13 21:57
MemberGregoryW8-Jul-13 21:57 
QuestionAdd the source code in downloadable format Pin
Tridip Bhattacharjee8-Jul-13 6:02
professionalTridip Bhattacharjee8-Jul-13 6:02 
AnswerRe: Add the source code in downloadable format Pin
josh-jw8-Jul-13 21:45
Memberjosh-jw8-Jul-13 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.