WebPages WebGrid

The WebGrid helper in ASP.NET WebPages is a powerful tool for displaying tabular data on your web pages. It supports features like sorting, paging, and custom formatting, making it ideal for creating dynamic data tables.

Key Topics

Creating a Basic WebGrid

Example

@{
    var data = new[]
    {
        new { Name = "John", Age = 30 },
        new { Name = "Jane", Age = 25 },
        new { Name = "Mike", Age = 35 }
    };

    var grid = new WebGrid(source: data);
}

@grid.GetHtml()

Explanation: This example demonstrates creating a basic WebGrid from an in-memory data source and rendering it on the page with GetHtml().

Customizing WebGrid Columns

Example

@{
    var data = new[]
    {
        new { Name = "John", Age = 30, Occupation = "Engineer" },
        new { Name = "Jane", Age = 25, Occupation = "Designer" },
        new { Name = "Mike", Age = 35, Occupation = "Manager" }
    };

    var grid = new WebGrid(source: data);
}

@grid.GetHtml(columns: grid.Columns(
    grid.Column("Name"),
    grid.Column("Occupation", format: @@item.Occupation.ToUpper())
))

Explanation: This example customizes the WebGrid by specifying which columns to display and adding formatting for the Occupation column to display text in uppercase.

Adding Pagination

Example

@{
    var data = Enumerable.Range(1, 100).Select(i => new { ID = i, Name = "Item " + i });

    var grid = new WebGrid(source: data, rowsPerPage: 10);
}

@grid.GetHtml()

Explanation: This example creates a WebGrid with pagination enabled, displaying 10 rows per page. The rowsPerPage parameter controls the number of rows shown on each page.

Key Takeaways

  • The WebGrid helper simplifies displaying tabular data with built-in support for sorting and paging.
  • You can customize column formatting using the grid.Column method.
  • Pagination makes it easier to navigate large datasets in a WebGrid.