Here, you’ll learn how to Grid View in blazor with Entity Framework Core in simple steps.

Check Part One of CRUD operation with Blazor.

Simple CRUD Operation With Blazor And Entity Framework Core.

Complete Source Code on Github

Project structure

Adding Interface IUserMasterQueries in BlazorPlayGround.Data Class Library

We have already added Folder UserMasters in BlazorPlayGround.Data Class Library and in that folder, we have 2 folders Command another Queries Folder.

Inside Queries Folder, we will add an Interface with the name IUserMasterQueries.

We will declare 2 methods in this interface.

  1. ShowTotalUsersCount :- Will Get total Users Count
  2. ShowAllUsers :- Will get a collection of UserMaster
using System.Collections.Generic;

namespace BlazorPlayGround.Data.UserMasters.Queries
{
    public interface IUserMasterQueries
    {
        int ShowTotalUsersCount(string search);
        List<Model.UserMasterModel> ShowAllUsers(string search, int pageNumber, int pageSize);
    }
}

Adding Class UserMasterQueries in BlazorPlayGround.Data Class Library

Inside Queries Folder, we will add a Class with the name UserMasterQueries, which will inherit the IUserMasterQueries interface.

We are using constructor injection for injecting BlazorPlayGroundContext dependency. 

UserMasterQueries Class will implement 2 methods that we have declared in IUserMasterQueries.

  •         int ShowTotalUsersCount(string search);

              ShowTotalUsersCount method takes one parameter as input search.

  •         List<Model.UserMasterModel> ShowAllUsers(string search, int pageNumber, int pageSize);

ShowAllUsers method takes 3 parameters as input and returns a List of Users based on parameters.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace BlazorPlayGround.Data.UserMasters.Queries
{
    public class UserMasterQueries : IUserMasterQueries
    {
        private readonly BlazorPlayGroundContext _blazorPlayGroundContext;
        public UserMasterQueries(BlazorPlayGroundContext blazorPlayGroundContext)
        {
            _blazorPlayGroundContext = blazorPlayGroundContext;
        }
        public int ShowTotalUsersCount(string search)
        {
            try
            {
                var queryable = (from usermaster in _blazorPlayGroundContext.UserMaster.AsNoTracking()

                        orderby usermaster.UserId descending
                        select usermaster
                    ).AsQueryable();

                if (!string.IsNullOrEmpty(search))
                {
                    queryable = queryable.Where(m => m.MobileNo.Contains(search) || m.MobileNo.Contains(search));
                }

                return queryable.Count();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public List<Model.UserMasterModel> ShowAllUsers(string search, int pageNumber, int pageSize)
        {
            try
            {
                var queryable = (from usermaster in _blazorPlayGroundContext.UserMaster.AsNoTracking()
                        orderby usermaster.UserId descending
                        select usermaster
                    ).AsQueryable();

                if (!string.IsNullOrEmpty(search))
                {
                    queryable = queryable.Where(m => m.MobileNo.Contains(search) || m.MobileNo.Contains(search));
                }

                var result = queryable.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Adding Component

We are going to add a Component with the name UserGridComponent.razor

Adding Base Class for UserGridComponentBase Component

We will add a class with the name UserGridComponentBase, and then we will inherit it with ComponentBase.

Next, we are going to add a property in the UserGridComponentBasecomponent.

Adding Property and Injecting dependencies

Injecting Dependency of IUserMasterQueries for accessing data to display on Grid

Injecting Dependency of IUserMasterCommand for deleting User Data by calling Delete method.

IJSRuntime Service is used to invoke any JavaScript function from .NET code.

NavigationManager Service is used for managing URIs and navigation.

[Inject] public IJSRuntime JsRuntime { get; set; }
[Inject] NavigationManager NavManager { get; set; }
[Inject] private IUserMasterQueries UserMasterQueries { get; set; }
[Inject] private IUserMasterCommand UserMasterCommand { get; set; }

Will add properties to Component for paging and send data to Page UserGridComponent.razor.

[Parameter] We can define a parameter to a component by applying the [Parameter] attribute.

[Parameter] public int Page { get; set; } = 1;
public int CurrentPage { get; set; } = 1;
public int Count { get; set; }
public int PageSize { get; set; } = 10;
public int TotalPages => (int)Math.Ceiling(decimal.Divide(Count, PageSize));
public List<UserMasterModel> Data { get; set; }
public string Search { get; set; }

Added BindGrid method to UserGridComponentBase Componet

The first Method we are going to Add is BindGrid which will get data that we are going assign to the property of component used on UserGridComponent.razor Page.

private void BindGrid()
{
    var result = UserMasterQueries.ShowAllUsers(Search, Page == 0 ? 1 : Page, PageSize).ToList();
    Count = UserMasterQueries.ShowTotalUsersCount(Search);
    Data = result;
    CurrentPage = Page;
}

Next, we are going to Call the BindGrid Method in the OnInitialized Method.

OnInitialized Method

protected override void OnInitialized()
{
     Page = 1;
     BindGrid();
}

OnParametersSet Method

OnParametersSet – Method invoked when the component has received parameters from its parent in the render tree and the incoming values have been assigned to properties.

This OnParametersSet Method will get called when we click on pagination links. Pagination links will have Page Parameter, which will get data from the database and display it.

protected override void OnParametersSet()
{
    BindGrid();
}

Search Method

SearchClick Method will be called when the user clicks on Search Button from UserGridComponent.razor Page.

In SearchClick Method, we are going to get the Search parameter which User has entered.

Search parameters are then passed to ShowAllUsers and ShowTotalUsersCount Method, filtering data and getting you to result.

 protected void SearchClick()
 {
     if (!string.IsNullOrEmpty(Search))
     {
         Page = 1;
         var result = UserMasterQueries.ShowAllUsers(Search, Page, PageSize).ToList();
         Count = UserMasterQueries.ShowTotalUsersCount(Search);
         Data = result;
         CurrentPage = Page;
     }
 }

Clear Method

Onclick of Clear Method, we will set grid values to default.

protected void ClearClick()
{
    Search = string.Empty;
    Page = 1;
    var result = UserMasterQueries.ShowAllUsers(Search, Page == 0 ? 1 : Page, PageSize).ToList();
    Count = UserMasterQueries.ShowTotalUsersCount(Search);
    Data = result;
    CurrentPage = Page;
}

Delete Method

Onclick of Delete Method we will Delete User from Database.

For deleting data first, we are going to declare the GetUserDetails method in IUserMasterQueries.

UserMasterModel GetUserDetails(int userId);

In Class UserMasterQueries, we are going to implement the GetUserDetails method.

Public UserMasterModel GetUserDetails(int userId)
{
     try
     {
         var edituser = (from usermaster in _blazorPlayGroundContext.UserMaster.AsNoTracking()
                 where usermaster.UserId == userId
                 select usermaster
             ).FirstOrDefault();

         return edituser;
     }
     catch (Exception)
     {
         throw;
     }
 }

AddingDelete method in UserGridComponentBase class. This method will be invoked with the click of the delete button. We will also get the Id (UserId of clicked row) parameter, which we will pass as an argument from the page.

Next, in the delete method, we will show a confirmation dialogue, and base on response, we will delete data and navigate it to another page using NavigationManager.

protected async void Delete(int id)
{
     bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?"); // Confirm
     if (confirmed)
     {
         var userdetails = UserMasterQueries.GetUserDetails(id);
         UserMasterCommand.Delete(userdetails);

         StateHasChanged();
         BindGrid();
         NavManager.NavigateTo("UserGrid", false);
     }
}

Complete Source Code of UserGridComponentBase

using System;
using System.Collections.Generic;
using System.Linq;
using BlazorPlayGround.Data.UserMasters.Command;
using BlazorPlayGround.Data.UserMasters.Queries;
using BlazorPlayGround.Model;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace BlazorPlayGround2.Pages
{
    public class UserGridComponentBase : ComponentBase
    {
        [Inject] public IJSRuntime JsRuntime { get; set; }
        [Inject] private IUserMasterQueries UserMasterQueries { get; set; }
        [Inject] private IUserMasterCommand UserMasterCommand { get; set; }
        [Inject] NavigationManager NavManager { get; set; }
        [Parameter] public int Page { get; set; } = 1;
        public int CurrentPage { get; set; } = 1;
        public int Count { get; set; }
        public int PageSize { get; set; } = 5;
        public int TotalPages => (int)Math.Ceiling(decimal.Divide(Count, PageSize));
        public List<UserMasterModel> Data { get; set; }
        public string Search { get; set; }

        protected override void OnInitialized()
        {
            Page = 1;
            BindGrid();
        }

        protected override void OnParametersSet()
        {
            BindGrid();
        }

        private void BindGrid()
        {
            var result = UserMasterQueries.ShowAllUsers(Search, Page == 0 ? 1 : Page, PageSize).ToList();
            Count = UserMasterQueries.ShowTotalUsersCount(Search);
            Data = result;
            CurrentPage = Page;
        }


        protected void SearchClick()
        {
            if (!string.IsNullOrEmpty(Search))
            {
                Page = 1;
                var result = UserMasterQueries.ShowAllUsers(Search, Page, PageSize).ToList();
                Count = UserMasterQueries.ShowTotalUsersCount(Search);
                Data = result;
                CurrentPage = Page;
            }
        }

        protected void ClearClick()
        {
            Search = string.Empty;
            Page = 1;
            var result = UserMasterQueries.ShowAllUsers(Search, Page == 0 ? 1 : Page, PageSize).ToList();
            Count = UserMasterQueries.ShowTotalUsersCount(Search);
            Data = result;
            CurrentPage = Page;
        }

        protected async void Delete(int id)
        {
            bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?"); // Confirm
            if (confirmed)
            {
                var userdetails = UserMasterQueries.GetUserDetails(id);
                UserMasterCommand.Delete(userdetails);

                StateHasChanged();
                BindGrid();
                NavManager.NavigateTo("UserGrid", false);

            }
        }
    }
}

Next, we will work on the UserGridComponent.razor page, which we have added earlier.

UserGridComponent.razor page

  1. Going to add the @page Razor directive and specify the route for Component (UserGrid)
  2. Going to add another @page directive to handle the route, which has the parameter Page “/UserGrid/{Page:int}”
  3. Adding @inherits directive and set base class for Component (UserGridComponentBase)

4. Add the Search Text box and button for search and clear.

<div class="form-row">
      <div class="form-group col-md-4">
          <input @bind-value="Search" class="form-control" type="text" placeholder="Filter...">
      </div>
      <div class="form-group col-md-4">
          <button class="btn btn-success" @onclick="SearchClick">Search</button>
          <button class="btn btn-danger" @onclick="ClearClick">Clear</button>
      </div>
</div>

5. Generating table for showing records here we are going to get List of UserMaster in Data Property which we are going to iterate and assign UserId parameter to Edit and Delete Method.

<table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>FirstName</th>
                            <th>MiddleName</th>
                            <th>LastName</th>
                            <th>EmailId</th>
                            <th>MobileNo</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        @{
                            int counter = 1;
                        }
                        @foreach (var usermaster in Data)
                        {

                            <tr @key="usermaster.UserId">
                                <td> @counter</td>
                                <td>@usermaster.FirstName</td>
                                <td>@usermaster.MiddleName</td>
                                <td>@usermaster.LastName</td>
                                <td>@usermaster.EmailId</td>
                                <td>@usermaster.MobileNo</td>
                                <td><a class="btn btn-warning" href="/EditUser/@usermaster.UserId">Edit</a></td>
                                <td><button type="button" class="btn btn-danger" @onclick="@(e => Delete(usermaster.UserId))">Delete</button></td>
                            </tr>

                            counter++;
                        }
                    </tbody>
</table>

6. Pagination

Using TotalPages, CurrentPage parameters, we are going to generate paging links.

<ul class="pagination">
    @for (var i = 1; i <= TotalPages; i++)
    {
        <li class="page-item @(i == CurrentPage ? "active" : "")">
            <a href="/UserGrid/@i" class="page-link">@i</a>
        </li>
    }
</ul>

Complete Source Code of UserGridComponent.razor page

@page "/UserGrid"
@page "/UserGrid/{Page:int}"

@inherits UserGridComponentBase
<div class="col-md-12">
    <div class="card">
        <div class="card-header">
            <h5 class="card-title">Grid</h5>
        </div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group col-md-4">
                    <input @bind-value="Search"
                           class="form-control" type="text" placeholder="Filter...">

                </div>
                <div class="form-group col-md-4">
                    <button class="btn btn-success" @onclick="SearchClick">Search</button>
                    <button class="btn btn-danger" @onclick="ClearClick">Clear</button>
                </div>
            </div>
            <div class="row">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>FirstName</th>
                            <th>MiddleName</th>
                            <th>LastName</th>
                            <th>EmailId</th>
                            <th>MobileNo</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        @{
                            int counter = 1;
                        }
                        @foreach (var usermaster in Data)
                        {

                            <tr @key="usermaster.UserId">
                                <td> @counter</td>
                                <td>@usermaster.FirstName</td>
                                <td>@usermaster.MiddleName</td>
                                <td>@usermaster.LastName</td>
                                <td>@usermaster.EmailId</td>
                                <td>@usermaster.MobileNo</td>
                                <td><a class="btn btn-warning" href="/EditUser/@usermaster.UserId">Edit</a></td>
                                <td><button type="button" class="btn btn-danger" @onclick="@(e => Delete(usermaster.UserId))">Delete</button></td>
                            </tr>

                            counter++;
                        }
                    </tbody>
                </table>

            </div>
            <div class="row">
                <ul class="pagination">
                    @for (var i = 1; i <= TotalPages; i++)
                    {
                        <li class="page-item @(i == CurrentPage ? "active" : "")">
                            <a href="/UserGrid/@i" class="page-link">@i</a>
                        </li>
                    }
                </ul>
            </div>
        </div>
    </div>
</div>

Now Let’s run the application and access / UserGrid Page.

Userful Links

PART 1 :- What is Blazor

PART 2 :- How to Create Blazor Server Application

PART 3 :- How to Create DropdownList in Blazor

PART 4 :- How to Create Radio Buttons in Blazor

PART 5 :- How to Create Checkbox in Blazor

PART 6 :- How to Create Cascading Dropdown List in Blazor

PART 7 :- How to Create CheckboxList In Blazor

Connect me on Github:- https://github.com/saineshwar

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.