In my opinion the documentation for MudDataGrid is a bit lacking when it comes to loading paged data from a dynamic source such as an API.
- How do I use the
ServerDataattribute? - How do I handle row clicks?
- How do I send additional filter / search criteria on the API call?
- How do I pre-set the
PageandPageSizeof theGridStateobject?
Let's say you want to make a blazor page that has a list of animals on it, displayed in a MudDataGrid. The animal data will come from an API.
How do I use the
ServerDataattribute?Firstly, define DTOs to handle the user's request, and the response from the API:
This, then, is the implementation of your MudDataGrid component in your blazor page:
As you can see, the Grid's
ServerDataattribute is set to call a method calledLoadGridData. We define that in our blazor page code:You need to create the
GetAnimalList()method that performs the API call, so on the server you would do your DB query and return aAnimalListDtoresult with theItemsandItemTotalCountproperties populated.After you've done that, congratulations! You have successfully implemented
ServerDatain MudDataGrid.How do I handle row clicks?
Say you want the user to view an animal when they click on a MudDataGrid row. Also you want to put a button on each row to allow the user to edit the animal if they click it.
Let's modify the MudDataGrid implementation in the blazor page code a little:
So now we have to implement a couple of new methods in our code:
How do I send additional filter / search criteria on the API call?
Now we want the user to be able to search the Animal data, by putting keywords into a search box.
Firstly we need to add a SearchTerm property to our request DTO:
Then, we add a form to the Blazor page, above the grid:
Now we add the
Searchmethod:Now the
SearchTermproperty is naturally sent along to the API call. You just need to modify your DB query to handle it.How do I pre-set the
PageandPageSizeof theGridStateobject?This might be a niche requirement, but you might want to use persisted state to pre-set the data grid to load a different page of data to the default. You might want to do this if the user has left the page, and then returned, expecting the data to be on the page where they left it.
Firstly, you need to load the state into the request DTO. So, you need to implement a state manager, e.g. an instance of type
GridDataRequestDtocalledAnimalListStatethat you inject into your page by adding a scopedMyStateHelperservice to your Program.csbuilder.Services. Then in your blazor page code:That way, the request DTO has been pre-populated when it comes to render time. So the final step is to to tell the DataGrid to pre-set the Page and PageSize. MudBlazor haven't given us a very nice way to do it, but I find that this approach works:
That's all folks. Please let me know if you have any problems.