Quick start with GridMvc

November 28, 2023 · View on GitHub

GridMvc for ASP.NET Core MVC

Quick start with GridMvc

Index

Imagine that you have to retrieve a collection of model items in your project. For example if your model class is:

    public class Foo
    {
        public string Title {get; set;}
        public string Description {get;set;}
    }

There are 2 methods to configure a grid on ASP.NET Core MVC:

  • Create a GridServer object on the controller and using a TagHelper
  • Create a Grid on the view using an HtmlHelper

Method 1: Create a GridServer object on the controller and using a TagHelper

The steps are:

  1. Your controller action has to create a GridServer object. The required parameters to create a GridServer object are a strongly-typed collection of the model items, the controller's request query and the columns definition. The view model must be the server's Grid object. An example of this type of controller action is:

        public class HomeController : Controller
        {
            private readonly FooRepository fooRepository;
    
            public HomeController(FooRepository fooRepository)
            {
                this.fooRepository = fooRepository;
            }
    
            public ActionResult Index()
            {
                IQueryable<Foo> items = fooRepository.GetAll();
                Action<IGridColumnCollection<Foo>> columns = c =>
                {
                    columns.Add(foo => foo.Title);
                    columns.Add(foo => foo.Description);
                };
                var server = new GridServer<Order>(items, Request.Query, false, "ordersGrid", columns);
    
                return View(server.Grid);
            }
        }
    
  2. And finally the view has to render the Grid. You can use a TagHelper. A simple view can be as follows:

        @using GridMvc
        @addTagHelper *, GridMvc
        @model ISGrid
    
        <grid model="@Model" />
    

Method 2: Create a Grid on the view using an HtmlHelper

The steps to build a Grid page are:

  1. Your controller action has to retrieve a strongly-typed collection of the model items and pass it to the view. An example of this type of controller action is:

        public class HomeController : Controller
        {
            private readonly FooRepository fooRepository;
    
            public HomeController(FooRepository fooRepository)
            {
                this.fooRepository = fooRepository;
            }
    
            public ActionResult Index()
            {
                IQueryable<Foo> items = fooRepository.GetAll();
                return View(items);
            }
        }
    
  2. And finally the view has to render your items collection. You can use an html helper extension.

    For ASP.NET Core MVC 2.x a simple view can be as follows:

        @using GridMvc
        @model IEnumerable<Foo>
    
        @Html.Grid(Model).Columns(columns =>
        {
            columns.Add(foo => foo.Title);
            columns.Add(foo => foo.Description);
        })
    

    Important: Synchronous operations are disallowed in ASP.NET Core MVC 3.x. So it´s recomended to use at least version 2.9.0 of the GridMvcCore nuget package and to add the asynchronuos RenderAsync method at the the end of the html helper to avoid InvalidOperationException associated with synchronous operations:

        @using GridMvc
        @model IEnumerable<Foo>
    
        @await Html.Grid(Model).Columns(columns =>
        {
            columns.Add(foo => foo.Title);
            columns.Add(foo => foo.Description);
        }).RenderAsync()
    

GridServer parameters

ParameterDescriptionExample
itemsIEnumerable object containing all the grid rowsrepository.GetAll()
queryIQueryCollection containing all grid parametersMust be the Request.Query of the controller
renderOnlyRowsboolean to configure if only rows are renderend by the server or all the grid objectMust be false for ASP.NET Core MVC solutions
gridNamestring containing the grid client nameordersGrid
columnslambda expression to define the columns included in the grid (Optional)Columns lamba expression defined in the razor page of the example
pageSizeinteger to define the number of rows returned by the web service (Optional)10
pagerViewNamestring to define the Pager (Optional)GridPager.DefaultPagerViewName or GridPager.DefaultAjaxPagerViewName

GridServer methods

Method nameDescriptionExample
AutoGenerateColumnsGenerates columns for all properties of the model using data annotationsGridServer(...).AutoGenerateColumns();
SortableEnable or disable sorting for all columns of the gridGridServer(...).Sortable(true);
SearchableEnable or disable searching on the gridGridServer(...).Searchable(true, true);
FilterableEnable or disable filtering for all columns of the gridGridServer(...).Filterable(true);
WithMultipleFiltersAllow grid to use multiple filtersGridServer(...).WithMultipleFilters();
SyncButtonEnable or disable the Sync button to refresh the gridGridServer(...).SyncButton(true);
ClearFiltersButtonEnable or disable the ClearFilters buttonGridServer(...).ClearFiltersButton(true);
SelectableEnable or disable the client grid items selectable featureGridServer(...).Selectable(true);
WithPagingEnable paging for gridGridServer(...).WithPaging(10);
SetLanguageSetup the language of the gridGridServer(...).SetLanguage('fr');
SetStripedConfigure the grid as stripedGridServer(...).SetStriped(true);
EmptyTextSetup the text displayed for all empty items in the gridGridServer(...).EmptyText(' - ');
WithGridItemsCountAllows the grid to show items countGridServer(...).WithGridItemsCount();
SetRowCssClassesSetup specific row css classesGridServer(...).SetRowCssClasses(item => item.Customer.IsVip ? "success" : string.Empty);
SetDirectionAllows the grid to be show in right to left directionGridServer(...).SetDirection(GridDirection.RTL);
SetTableLayoutConfigure fixed dimensions for the gridGridServer(...).SetTableLayout(TableLayout.Fixed, "1200px", "400px");

Grid configuration

You can use multiple methods of the SGrid object to configure a grid. For example:

    @Html.Grid(Model).Columns(columns =>
    {
       columns.Add(foo => foo.Title);
       columns.Add(foo => foo.Description);
    }).WithPaging(10).SetLanguage("fr").Sortable().Filterable().WithMultipleFilters().Render()

Grid methods

Method nameDescriptionExample
NamedSetup the grid client nameHtml.Grid(Model).Named("Product List");
ColumnsSetup the grid client nameHtml.Grid(Model).Columns(...);
AutoGenerateColumnsGenerates columns for all properties of the model using data annotationsHtml.Grid(Model).AutoGenerateColumns();
SortableEnable or disable sorting for all columns of the gridHtml.Grid(Model).Sortable(true);
SearchableEnable or disable searching on the gridHtml.Grid(Model).Searchable(true, true);
FilterableEnable or disable filtering for all columns of the gridHtml.Grid(Model).Filterable(true);
WithMultipleFiltersAllow grid to use multiple filtersHtml.Grid(Model).WithMultipleFilters();
SelectableEnable or disable the client grid items selectable featureHtml.Grid(Model).Filterable(true);
WithPagingEnable paging for gridHtml.Grid(Model).WithPaging(10);
SetLanguageSetup the language of the gridHtml.Grid(Model).SetLanguage('fr');
SetStripedConfigure the grid as stripedHtml.Grid(Model).SetStriped(true);
EmptyTextSetup the text displayed for all empty items in the gridHtml.Grid(Model).EmptyText(' - ');
WithGridItemsCountAllows the grid to show items countHtml.Grid(Model).WithGridItemsCount();
SetRowCssClassesSetup specific row css classesHtml.Grid(Model).SetRowCssClasses(item => item.Customer.IsVip ? "success" : string.Empty);
SetDirectionAllows the grid to be show in right to left directionHtml.Grid(Model).SetDirection(GridDirection.RTL);
SetTableLayoutConfigure fixed dimensions for the gridHtml.Grid(Model).SetTableLayout(TableLayout.Fixed, "1200px", "400px");

For more documentation about column options, please see: Custom columns.

<- Installation | Paging ->