In ASP.NET, a WebGrid is a helper component that simplifies the process of displaying tabular data in a web page. It generates HTML markup for a grid-based layout, allowing you to easily render data from a collection or database query in a table format. Let's explain with an example:
Example: Displaying a List of Products using WebGrid
Suppose you have a list of products and you want to display them in a table on your web page using the WebGrid helper.
First, ensure you have the necessary namespaces imported in your ASP.NET page:
Example
<%@ Import Namespace="System.Web.Helpers" %>
Then, you can use the WebGrid helper to display the list of products:
Example
@{
// Define a list of products
var products = new List<Product>
{
new Product { Id = 1, Name = "Product 1", Price = 10.99 },
new Product { Id = 2, Name = "Product 2", Price = 20.99 },
new Product { Id = 3, Name = "Product 3", Price = 30.99 }
};
// Create a WebGrid instance
var grid = new WebGrid(source: products, rowsPerPage: 5);
}
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h2>Product List</h2>
<!-- Display the WebGrid -->
@grid.GetHtml(
columns: grid.Columns(
grid.Column("Id", "Product ID"),
grid.Column("Name", "Product Name"),
grid.Column("Price", "Price")
)
)
</body>
</html>
In this example:
grid
, passing the list of products as the data source and specifying the number of rows per page.@grid.GetHtml()
to render the WebGrid. We specify the columns we want to display using grid.Columns()
, providing the property names and column headings.When you run this ASP.NET page, it will display the list of products in a table format, with columns for Product ID, Product Name, and Price.
WebGrid simplifies the process of creating tables for displaying data in ASP.NET web pages, offering features like sorting, paging, and column customization out of the box. It's a convenient tool for presenting tabular data in a user-friendly manner.