Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

WebGrid is the System.Web.Helpers.WebGrid helper for rendering a collection as an HTML table in an ASP.NET MVC 5 Razor view. Create it from your view model’s collection, enable only the paging and sorting behavior you need, then call GetHtml(). For large result sets, retrieve one page in the controller or data-access layer and provide WebGrid with the total row count instead of loading every record.

What WebGrid does

Microsoft describes WebGrid as displaying data on a web page with an HTML table element. It is a view-rendering helper, not an MVC controller feature and not a database paging engine. The API is documented under System.Web.Helpers.WebGrid.

WebGrid can render selected columns, headers, links, CSS classes, pager controls and HTML attributes. Its constructor accepts a data source and options such as the default sort expression, rows per page, and whether paging and sorting are enabled. The documented default page size is 10 rows.

References and namespaces to verify first

The WebGrid API is part of the ASP.NET Web Pages assemblies commonly used by MVC 5 applications. Microsoft’s reference page shows Microsoft.AspNet.WebPages 3.2.6 metadata, while the MVC HtmlHelper reference shows Microsoft.AspNet.Mvc 5.2.6 metadata. Those page versions describe the reference documentation; they do not prove that your project uses those exact package versions. Check the project’s existing references and package configuration before changing them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Your Razor view must be able to resolve WebGrid, either through the project’s configured namespaces or with an explicit import such as:

@using System.Web.Helpers

Use the actual assembly and namespace configuration of the application rather than copying a package version from the documentation.

Minimal MVC 5 implementation

1. Define a view model

Expose the collection that the view will display. The property names in this example are illustrative; replace them with your application’s model.

public class CustomerListViewModel
{
    public IEnumerable<Customer> Items { get; set; }
}

2. Populate it in the controller

public ActionResult Index()
{
    var model = new CustomerListViewModel
    {
        Items = customerService.GetCustomers()
    };

    return View(model);
}

3. Construct and render WebGrid in the Razor view

@using System.Web.Helpers
@model CustomerListViewModel

@{
    var grid = new WebGrid(
        source: Model.Items,
        rowsPerPage: 10,
        canPage: true,
        canSort: true);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("Name", header: "Name"),
        grid.Column("Created", header: "Created")))

Model.Items, Name, and Created must match the collection and properties in your application. The constructor and rendering signatures are documented in Microsoft’s WebGrid constructor reference and GetHtml method reference. Microsoft’s MVC example is archived in ASP.NET WebGrid: Get the Most out of WebGrid in ASP.NET MVC.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choosing columns and presentation

Pass only the columns users need to grid.Columns(...). This prevents internal fields from appearing accidentally and gives you control over labels. GetHtml also accepts exclusions, style settings, pager mode and pager text, and HTML attributes.

@grid.GetHtml(
    tableStyle: "table table-striped",
    headerStyle: "table-header",
    alternatingRowStyle: "table-alternate",
    columns: grid.Columns(
        grid.Column("Name", header: "Customer"),
        grid.Column("Created", header: "Created on")))

Use the overload and option names supported by the WebGrid version referenced by the application. The documented default pager combines previous/next navigation with numeric links; choose a different pager presentation when your layout requires it.

Paging and sorting for an in-memory collection

When the controller already has a modest collection, WebGrid can page and sort the supplied items:

  • Set rowsPerPage to the page length you want.
  • Set canPage: true to render navigation.
  • Set canSort: true to allow sortable columns.
  • Use defaultSort when the initial ordering should be explicit.

This approach is simple, but all records have already been loaded before WebGrid renders the requested page. It is therefore unsuitable when the underlying query can return a large result set.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Server-side paging for large result sets

For a large table, let the data-access path fetch only the requested slice. The action reads the requested page and sort state, applies a deterministic query, and obtains the overall row count separately. WebGrid still needs that count to know how many pages exist.

Controller and service responsibilities

  1. Read the page number and sort value from the request using the field names configured for the grid.
  2. Validate those values against permitted page sizes and sortable columns.
  3. Apply ordering before taking the page slice in the data layer.
  4. Return the page items and the total number of matching rows.
  5. Bind the page items to WebGrid with automatic sorting and paging disabled, while supplying the total row count.

The archived Microsoft MVC article illustrates this pattern: retrieve the requested slice, pass the total count, and call Bind with autoSortAndPage: false. Without the total count, WebGrid sees only the rows in the current slice and cannot generate links to pages it does not know exist.

Illustrative Razor shape

@using System.Web.Helpers
@model CustomerPageViewModel

@{
    var grid = new WebGrid(
        canPage: true,
        canSort: true,
        rowsPerPage: Model.PageSize);

    grid.Bind(
        source: Model.Items,
        rowCount: Model.TotalCount,
        autoSortAndPage: false);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("Name", header: "Name"),
        grid.Column("Created", header: "Created")))

Adapt the binding call to the exact overload available in the project’s Web Pages reference. The important design is that the service performs the slice and ordering, while WebGrid receives the current page plus the total count for pager generation.

Keep server-side sorting consistent

If paging is server-side, sorting must be server-side as well. Apply a validated sort expression before selecting the page; otherwise a user can move between pages whose ordering is inconsistent. The WebGrid helper does not know how to translate an arbitrary sort request into an efficient database query.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Query-string state and multiple grids

WebGrid uses query-string fields for page, selection and sorting state. The API allows those field names to be customized, including a prefix. Configure distinct names when one page contains multiple grids; otherwise one grid’s navigation can overwrite or be mistaken for another grid’s state. Confirm the generated links and route behavior in the actual application.

Full collection or server-side page?

Approach What reaches the view Advantages Costs and risks
WebGrid over full collection Every matching row Smallest implementation; WebGrid handles paging and sorting over the supplied items. Loading and transferring a large collection consumes database, service, memory and rendering resources.
Server-side paging Requested slice plus total row count Limits work to the current page and still lets WebGrid render accurate navigation. Requires validated page/sort parameters, stable data-layer ordering and a reliable count query.

Use the first approach only when the collection is sufficiently small and already loaded for another reason. Prefer the second when the result set can grow or the query is expensive.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common integration problems

The grid renders one page only

With server-side paging, check that the total matching row count is passed to Bind. Supplying only the current slice leaves WebGrid with no evidence that additional pages exist.

Sorting changes the wrong grid

Inspect the generated query-string names. Assign a different prefix or distinct page/sort field names to each grid on the page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Rows or properties are missing

Verify that the source collection is non-null and that each column name matches a readable property. Replace the sample names in the view with the actual model properties.

Unexpected database load

A rowsPerPage setting does not by itself make the database query paged. If the controller loads every record first, WebGrid is only paginating in memory. Move filtering, ordering, slicing and counting into the service or data-access layer.

Namespace or assembly errors

Confirm that the project references the ASP.NET Web Pages component containing System.Web.Helpers.WebGrid, and that the Razor view can resolve the namespace. Compare the project’s MVC and Web Pages references with the APIs documented by Microsoft rather than assuming the metadata versions on the reference pages are installed.

Implementation checklist

  • Use a strongly typed view model with the collection the grid should display.
  • Reference and import System.Web.Helpers as required by the project.
  • Set rowsPerPage, canPage, canSort and defaultSort deliberately.
  • Declare the displayed columns explicitly with grid.Columns.
  • Use full-collection paging only for appropriately small result sets.
  • For large sets, fetch one page, apply sorting in the data layer and pass the total row count.
  • Use unique query-string field names or prefixes when multiple grids share a page.
  • Test generated pager and sort links against the application’s routes and filters.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.