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>();
})
);
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.
Paging
bool
Enables paging on the grid
ItemsPerPage
int
Number of items to display on each page
Sorting
bool
Enables sorting on the grid. Note, sorting must also be enabled on each column where sorting is wanted
DefaultSortColumn
string
The default column to sort by when no sort is specified
Filtering
bool
Enables filtering on the grid. Note, filtering must also be enabled on each column where filtering is wanted
PreloadData
bool
Enables data loading when the page is first loaded so that the initial ajax request can be skipped.
QueryStringPrefix
string
A prefix to add to all query string paramters for this grid, for when there are more than 1 grids on the same page
NoResultsMessage
string
Text to display when there are no results.
ClientSideLoadingMessageFunctionName
string
Name of function to call before ajax call begins
ClientSideLoadingCompleteFunctionName
string
Name of function to call before ajax call ends
RowCssClassExpression
Func<T1, GridContext, string>
Use this to specify a custom css class based on data for the current row
AdditionalSettings
Dictionary<string, string>
Arbitrary additional settings for this grid
RenderingMode
RenderingMode
The 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
ViewPath
string
When RenderingMode is set to Controller, this is the path to the razor view to use.
ErrorMessageHtml
string
HTML to display in place of the grid when an error occurs
AdditionalQueryOptionNames
HashSet<string>
Names of additional parameters that can be passed from client to server side
AllowChangingPageSize
bool
Allows changing of page size from client-side
MaxItemsPerPage
int?
Sets the maximum of items per page allowed when AllowChangingPageSize is enabled
Set 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.
PageIndex
int?
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.
ItemsPerPage
int?
Set to null if paging is disabled. Otherwise it is set to the ItemPerPage specified in the grid
Filters
Dictionary<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)
string
Use this to check for a filter on a column. Will return null if the column has no filter specified.
SortColumnData
object
The object from the ColumnDefinition of the currently sorted coumn, if different from the ColumnName
AdditionalQueryOptions
Dictionary<string,string>
additional parameters that can be passed from client to server side
data-mvcgrid-type='filter' - data-mvcgrid-option='ColumnName' - put these attributes on any input element whose value you want to be a filter parameter.
data-mvcgrid-type='additionalQueryOption' - data-mvcgrid-option='ColumnName' - put these attributes on any input element whose value you want to be an additional query parameter.
data-mvcgrid-apply-filter='event' - put these attributes on a button or input element that you want to trigger filtering. For example, a button click or select list change. Fill in the event name with click, change, keyup, etc to control the trigger.
data-mvcgrid-apply-additional='event' - put these attributes on a button or input element that you want to trigger applying of additional query parameters.
data-mvcgrid-type='export' - put this attribute on a button to trigger the export to csv.
data-mvcgrid-type='pageSize' - put this attribute on a select list to bind to the current page side. On change will trigger updating the grid.
data-mvcgrid-type='columnVisibilityList' - put this attribute on a <ul> element. List items will be appended with checkboxes to change column visibility.
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)
);