Documentation

Grid Configuration

Upon installing the NuGet package, the file MVCGridConfig.cs will be added to the App_Start folder. Inside the RegisterGrids method, configure the settings for each grid you want to create.

Basic Usage
MVCGridDefinitionTable.Add("UsageExample", new MVCGridBuilder<YourModelItem>()
    .WithAuthorizationType(AuthorizationType.AllowAnonymous)
    .AddColumns(cols =>
    {
        // Add your columns here
        cols.Add("UniqueColumnName").WithHeaderText("Any Header")
            .WithValueExpression(i => i.YourProperty); // use the Value Expression to return the cell text for this column
        cols.Add().WithColumnName("UrlExample")
            .WithHeaderText("Edit")
            .WithValueExpression((i, c) => c.UrlHelper.Action("detail", "demo", new { id = i.YourProperty }));
    })
    .WithRetrieveDataMethod((context) =>
    {
        // Query your data here. Obey Ordering, paging and filtering paramters given in the context.QueryOptions.
        // Use Entity Framwork, a module from your IoC Container, or any other method.
        // Return QueryResult object containing IEnumerable<YouModelItem>
        return new QueryResult<YourModelItem>()
        {
            Items = new List<YourModelItem>(),
            TotalRecords = 0 // if paging is enabled, return the total number of records of all pages
        };
    })
);
        

Setting Defaults

To set defaults for multiple grids, create a GridDefaults object and set the desired properties. Then pass that GridDefaults object into the GridBuilder or GridDefinition when creating it.

GridDefaults gridDefaults = new GridDefaults()
{
	Paging = true,
	ItemsPerPage = 20,
	Sorting = true,
	NoResultsMessage = "Sorry, no results were found"
};
ColumnDefaults colDefaults = new ColumnDefaults()
{
    EnableSorting = true
};
MVCGridDefinitionTable.Add("UsageExample",
	new MVCGridBuilder<YourModelItem>(gridDefaults, colDefaults) // pass in defaults object to ctor
	.AddColumns(cols =>
	{
		// add columns
	})
	.WithRetrieveDataMethod((context) =>
	{
		//get data
		return new QueryResult<YourModelItem>();
	})
);

Grid Definition

Name Return Type Description
RetrieveDataFunc<GridContext, QueryResult<T1>>This is the method that will actually query the data to populate the grid. Use entity framework, a module from you IoC container, direct SQL queries, etc. to get the data. Inside the providee GridContext there is a QueryOptions object which will be populated with the currently requested sorting, paging, and filtering options which you must take into account. See the QueryOptions documentation below. You must return a QueryResult object which takes an enumerable of your type and a count of the total number of records which must be provided if paging is enabled.
PagingboolEnables paging on the grid
ItemsPerPageintNumber of items to display on each page
SortingboolEnables sorting on the grid. Note, sorting must also be enabled on each column where sorting is wanted
DefaultSortColumnstringThe default column to sort by when no sort is specified
FilteringboolEnables filtering on the grid. Note, filtering must also be enabled on each column where filtering is wanted
PreloadDataboolEnables data loading when the page is first loaded so that the initial ajax request can be skipped.
QueryStringPrefixstringA prefix to add to all query string paramters for this grid, for when there are more than 1 grids on the same page
NoResultsMessagestringText to display when there are no results.
ClientSideLoadingMessageFunctionNamestringName of function to call before ajax call begins
ClientSideLoadingCompleteFunctionNamestringName of function to call before ajax call ends
RowCssClassExpressionFunc<T1, GridContext, string>Use this to specify a custom css class based on data for the current row
AdditionalSettingsDictionary<string, string>Arbitrary additional settings for this grid
RenderingModeRenderingModeThe rendering mode to use for this grid. By default it will use the RenderingEngine rendering mode. If you want to use a custom Razor view to display your grid, change this to Controller
ViewPathstringWhen RenderingMode is set to Controller, this is the path to the razor view to use.
ErrorMessageHtmlstringHTML to display in place of the grid when an error occurs
AdditionalQueryOptionNamesHashSet<string>Names of additional parameters that can be passed from client to server side
AllowChangingPageSizeboolAllows changing of page size from client-side
MaxItemsPerPageint?Sets the maximum of items per page allowed when AllowChangingPageSize is enabled

Column Definition

Name Return Type Description
ColumnNamestringA unique name for this column
HeaderTextstringHeader text to display for the current column, if different from ColumnName
ValueExpressionFunc<T1, GridContext, string>This is how to specify the contents of the current cell. If this contains HTML, set HTMLEncode to false
PlainTextValueExpressionFunc<T1, GridContext, string>This is how to specify the contents of the current cell when used in an export file, if different that ValueExpression
CellCssClassExpressionFunc<T1, GridContext, string>Use this to specify a custom css class based on data for the current cell
ValueTemplatestringTemplate for formatting cell value
EnableSortingboolEnables sorting on this column
EnableFilteringboolEnables filtering on this column
HtmlEncodeboolDisables html encoding on the data for the current cell. Turn this off if your ValueExpression returns HTML.
VisibleboolIf the current column is visbile
SortColumnDataobjectObject to pass to QueryOptions when this coumn is sorted on. Only specify if different from ColumnName

QueryOptions

Name Return Type Description
SortColumnstringSet to null if sorting is disabled. If sorting is enabled, the requested sort column is validated against the list of column names and only set if it is valid and sorting is enabled on that column.
PageIndexint?Set to null if paging is disabled. Parsed from the request and set to the requested page index. If less than 0, it is set to 0.
ItemsPerPageint?Set to null if paging is disabled. Otherwise it is set to the ItemPerPage specified in the grid
FiltersDictionary<string, string>Set to an empty dictionary if filtering is disabled. If filtering is enabled, the requested filters are validated against the list of column names and the key is set to the column name if the column name is valid and filtering is enabled on that column. The filter dictionaty item is not added if the value is null or empty.
GetFilterString(string columnName)stringUse this to check for a filter on a column. Will return null if the column has no filter specified.
SortColumnDataobjectThe object from the ColumnDefinition of the currently sorted coumn, if different from the ColumnName
AdditionalQueryOptionsDictionary<string,string>additional parameters that can be passed from client to server side

Client-Side API

Name Description
MVCGrid.getFilters(mvcGridName)
MVCGrid.setFilters(mvcGridName, obj)
MVCGrid.setSort(mvcGridName, sortColumn, sortDirection)
MVCGrid.getSortColumn(mvcGridName)
MVCGrid.getSortDirection(mvcGridName)
MVCGrid.getPage(mvcGridName)
MVCGrid.setPage(mvcGridName, page)
MVCGrid.getPageSize(mvcGridName)
MVCGrid.setPageSize(mvcGridName, pageSize)
MVCGrid.getAdditionalQueryOptions(mvcGridName)
MVCGrid.setAdditionalQueryOptions(mvcGridName, obj)

Client-Side Bindings

Debugging Grid Errors

Add the following appSetting to your web.config file to see the actual error details on grid generation instead of the custom error message: <add key="MVCGridShowErrorDetail" value="true" />

Code used to generate the 3 above grids:

Just because I could

var docsReturnTypeColumn = new GridColumn<methoddocitem>()
{
    ColumnName = "ReturnType",
    HeaderText = "Return Type",
    HtmlEncode = false,
    ValueExpression = (p, c) => String.Format("<code>{0}</code>", HttpUtility.HtmlEncode(p.Return))
};
var docsNameColumn = new GridColumn<methoddocitem>()
{
    ColumnName = "Name",
    HtmlEncode = false,
    ValueExpression = (p, c) => String.Format("<code>{0}</code>", HttpUtility.HtmlEncode(p.Name))
};
var docsDescriptionColumn = new GridColumn<methoddocitem>()
{
    ColumnName = "Description",
    ValueExpression = (p, c) => p.Description
};
Func<gridcontext, queryresult<MethodDocItem>> docsLoadData = (context) =>
{
    var result = new QueryResult<MethodDocItem>();
    DocumentationRepository repo = new DocumentationRepository();
    result.Items = repo.GetData(context.GridName);
    return result;
};
MVCGridDefinitionTable.Add("GridDefinition", new MVCGridBuilder<MethodDocItem>()
    .AddColumn(docsReturnTypeColumn)
    .AddColumn(docsNameColumn)
    .AddColumn(docsDescriptionColumn)
    .WithRetrieveDataMethod(docsLoadData)
);
MVCGridDefinitionTable.Add("GridColumn", new MVCGridBuilder<MethodDocItem>()
    .AddColumn(docsReturnTypeColumn)
    .AddColumn(docsNameColumn)
    .AddColumn(docsDescriptionColumn)
    .WithRetrieveDataMethod(docsLoadData)
);
MVCGridDefinitionTable.Add("QueryOptions", new MVCGridBuilder<MethodDocItem>()
    .AddColumn(docsReturnTypeColumn)
    .AddColumn(docsNameColumn)
    .AddColumn(docsDescriptionColumn)
    .WithRetrieveDataMethod(docsLoadData)
);