WebGrid in ASP.NET MVC

Sheonarayan
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 30756 red flag
Rating: 5 out of 5  
 3 vote(s)

In this article, we shall learn how to work with WebGrid in ASP.NET MVC ie. we shall learn how to sort, paginate, specify column names, format column styles, making SEO friendly listing of data in ASP.NET MVC.
Recommendation
Read Using Angular $http.put with ASP.NET MVC project before this article.

Introduction

Grid is most powerful tools to list records from database in any web application. Like ASP.NET Web Forms GridView, DataList, ASP.NET MVC didn't had any built in data controls. Thanks to WebGrid that does almost all work of ASP.NET Web Form GridView and it is simple enough too.

In this article, we shall learn following
  1. How to simply list data in Grid
  2. How to achieve sorting and SEO friendly pagination
  3. Grid with custom column names
  4. AJAX Pagination & sorting
  5. Formatting web grid columns styles
  6. Selecting a record from WebGrid

Setting up the WebGrid demo

Let's start with setting up the demo. First we have to create an action method in the controller that returns collection of data (model). For this demo, its pretty simple.

Controller

public ActionResult WebGrid()
        {
            var data = db.PersonalDetails.ToList();
            return View(data);
        }

This simply gets PersonalDetails records from the database and return to the view.

View

@model IEnumerable<WebApplication1.Models.PersonalDetail>
As the controller action method returns collection of PersonalDetail model so our view will have above @model directive.


Getting started with WebGrid

Now let us learn how to achieve different different functionalities using WebGrid in ASP.NET MVC.

Simply list data in WebGrid with auto sorting and paging


To simply list data in Grid, instantiate WebGrid and pass Model (collection of Model object) as parameter and then use GetHtml() method in the View page.

@{
    ViewBag.Title = "WebGrid";
    WebGrid grid = new WebGrid(Model); // grid with sorting and paging    
}

@grid.GetHtml()
This will list the data from the database that looks something like below. Note that sorting and paging is by default enabled in the WebGrid.

Listing the data without sorting but with paging

To list data without sorting but with paging, simply set canSort property to false in the WebGrid instance.

@{
    ViewBag.Title = "WebGrid";
    WebGrid grid = new WebGrid(Model, canSort : false); // grid with paging but not sorting
}

@grid.GetHtml()

Listing data with default sort on specific field

To list data with default sort on specific field, set defaultSort property to the field name on which we want to sort.

WebGrid grid = new WebGrid(Model, defaultSort : "FirstName"); // grid with default sort on FirstName

Setting rows per page in WebGrid

To set rows per page to display in the WebGrid, set rowsPerPage property to the instance of the WebGrid.

WebGrid grid = new WebGrid(Model, defaultSort: "FirstName", rowsPerPage : 5); 
// grid with default sort on FirstName and 5 rows per page
This will display 5 records per page in the Grid that will be sorted by FirstName by default.

Displaying only specific columns in the WebGrid

To display only specific columns to the WebGrid from the data source, we can set columnNames property to the instance of the WebGrid.

WebGrid grid = new WebGrid(Model, defaultSort: "FirstName", rowsPerPage : 5, columnNames : new[] { "FirstName", "LastName"}); 
// grid with default sort on FirstName, rows per page, column names

Above code snippet shall display only FirstName and LastName columns from the Model collection as shown below.


Specifying custom header in the WebGrid columns

To specify custom headers to the WebGrid columns, we can pass columns property to the GetHtml() method in the View.

@grid.GetHtml(columns : grid.Columns(grid.Column("FirstName", header : "First Name"),
                            grid.Column("LastName", "Last Name"),
                            grid.Column("Age", "AGE"),
                           grid.Column("Active", "ACTIVE")))

Notice that in the above code snippet, we have set columns property to grid.Columns by passing array of grid.Column that accepts actual column name and header to set for them.

Setting CSS class name for grid, rows, columns etc.

To set up CSS class name for the grid table element, header, footer, rows, alternate row styles we can set respective properties.

@grid.GetHtml(tableStyle : "gTable")
This code will set up grid (that actually renders as html <table> element) css class attribute to "gTable".

Similarly, we can also set following property for the respective style\
  • headerStyle - for header of the webgrid
  • footerStyle - for footer of the webgrid
  • rowStyle - for rows of the webgrid
  • alternateRowStyle - for alternate rows of the webgrid
  • selectedRowStyle - for selected row of the webgrid

Selecting a row from the WebGrid using link

To provide selection ability to the Grid, we can set columns property with grid.Column and specify format by calling GetSelectLink method. Notice the first Column (Auto Id) specified as Select link that makes that column value as clickable.

@{
    ViewBag.Title = "WebGrid";
    WebGrid grid = new WebGrid(Model); // grid with sorting and paging
}

<div id="tblGrid">
    @grid.GetHtml(tableStyle : 
        "gTable", columns: grid.Columns(grid.Column("Auto Id", format :(item) => item.GetSelectLink(item.AutoId.ToString())),
        grid.Column("LastName", "Last Name"),
        grid.Column("Age", "AGE"),
        grid.Column("Active", "ACTIVE")), selectedRowStyle : "selectedRow")
</div>

<h3>Selected row</h3>
@if (grid.HasSelection)
{
    var pd = (WebApplication1.Models.PersonalDetail) grid.Rows[grid.SelectedIndex].Value;
    <p>Auto Id: @pd.AutoId</p>
    <p>First Name: @pd.FirstName</p>
    <p>Last Name: @pd.LastName</p>
    <p>Age: @pd.Age</p>
}

Once user click on the (Auto Id) column link, he/she sees the details of that records below the grid that is written under grid.HasSelection condition.


Adding custom column in WebGrid

To add a custom column to the WebGrid, we can use grid.Column method by setting format attribute to the template we want to use.

@grid.GetHtml(columns : grid.Columns(grid.Column("FirstName", header : "First Name"),
     grid.Column("LastName", "Last Name"),
     grid.Column("Age", "AGE"),
    grid.Column("Active", "ACTIVE"),
    grid.Column(header : "Edit", format : (item) => {
        var link = Html.ActionLink("Edit", "Edit", new { id = item.AutoId });
        return link;}),
        
     grid.Column("My Age", format: a => GetCustomData(a.Age))
    ))

Notice the bold code in the above code snippet, the "Edit" column writes the "Edit" link and "My Age" column writes below GetCustomData custom helper method data. 

@helper GetCustomData(dynamic age) { 
    <text>My Age: @age </text>
    }

Look at below code snippet, where we have Edit and My Age column.


WebGrid using Ajax


If we want to do pagination, sorting in WebGrid using Ajax (without page refresh), we can simply set the ajaxUpdateContainerId property to the HTML element id inside which we want to populate tabular data.

@{
      WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "tblGrid"); 
}

<div id="tblGrid">
    @grid.GetHtml(tableStyle: "gTable")
</div>

Now, clicking on the header link and paging link, respective functionality works without page refresh.

CSS class used for above Grid is below


To decorate the WebGrid that is shown above, I have used below CSS classes.

<style>
    .gTable {
        border-collapse: collapse;
        border: 1px solid #c0c0c0;
        width: 100%;
    }

        .gTable tr td {
            padding: 5px;
            border: 1px solid #c0c0c0;
        }

        .gTable tr:nth-child(2n+1) {
            background-color: #eaeaea;
        }

        .gTable tr th {
            background-color: #8fd9ff;
        }

    tfoot tr td {
        background-color: #ffd800 !important;
    }

    .gTable tr:hover {
        background-color: #fffddc;
    }

    .selectedRow {
        background-color: #ff6a00 !important;
    }
</style>

Summary

In this article, we have seen how to list data in tabular format and achieve sorting, paging and other functionality in ASP.NET MVC using WebGrid.

Feel free to download the attachment that contains the Views used to demonstrate above examples. The Controller action method is simply returning all data from database using Entity Framework as shown in the 1st code snippet above.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Sarvesh311 on: 9/11/2015 | Points: 25
I searched a lot for this but couldn't find solution. I have used Boostrap Modal popup in asp.net mvc 4 application along with Webgrid. I created partial view for edit and using jquery,ajax I am injecting html in the modal popup.

The edit modal popup shows correctly on first page; but on page 2 or any page other than page 1,it doesn't

I would appreciate if you could help me or give me slight idea. My code is very similar as on this http://www.advancesharp.com/blog/1125/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-1

Login to post response

Comment using Facebook(Author doesn't get notification)