Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WebGrid in ASP.NET MVC4

0.00/5 (No votes)
14 Jul 2013 3  
This tip will help you to develop a webgrid in ASP.NET MVC application.

Introduction  

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.

Product.cs

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public long Quantity { get; set; }
} 
Colourised in 3ms

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

InventoryController.cs

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);
}  
Colourised in 26ms

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

WebgridSample.cshtml:

@{
    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, 
    selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
        grid.Pager(WebGridPagerModes.NextPrevious);} 
Colourised in 1ms

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}
</style> 
Colourised in 7ms

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")
     )) 
</div>
Colourised in 3ms

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)) 
Colourised in 1ms

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 />
}
Colourised in 5ms

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"
Colourised in 0ms

Add a reference to jQuery.

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

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",
                "htmlArguments"
                )
Colourised in 2ms
                
grid.Column("Detail", format: @<text>@Html.ActionLink("Select", "Submit",
                new { QtId = item.QtId }) </text>),
Colourised in 2ms

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

History

  • 4th July, 2013: Initial post.

This tip is based on this blog.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here