Understanding CRUD Operation in Blazor

In this article, you will get answers to the following questions.

  1. How to create a table using a query?
  2. How to set a database connection and fetch for operations?
  3. Which NuGet packages are required?
  4. What are services?
  5. How to register services in Program.cs?
  6. How to implement CRUD operation in Blazor?
  7. How to Redirect to Other Components?

Before proceeding to this article, kindly refer to my previous articles,

Part 1. Overview of Blazor.

https://www.c-sharpcorner.com/article/overview-of-blazor2/

Part 2. Overview and Project Understanding of Blazor Server App.

https://www.c-sharpcorner.com/article/understanding-of-blazor-server-app-project-structure/

Part 3. Blazor Component: Creation, Lifecycle, Nesting, & UI Integration.

https://www.c-sharpcorner.com/article/blazor-component-creation-lifecycle-nesting-ui-integration/

Part 4. Form Controls in Blazor.

https://www.c-sharpcorner.com/article/form-controls-and-create-basic-form-in-blazor-component/

How to create a table using a query?

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblEmployees](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [nvarchar](100) NULL,
[Address] [nvarchar](500) NULL,
[City] [nvarchar](50) NULL,
[State] [nvarchar](50) NULL,
[Country] [nvarchar](50) NULL,
[Mobile] [nvarchar](20) NULL,
[EmailID] [nvarchar](200) NULL
) ON [PRIMARY]
GO

First, create a table called “tblEmployees” in your database.

Insert Query

GO

SET IDENTITY_INSERT [dbo].[tblEmployees] ON

INSERT [dbo].[tblEmployees] ([EmployeeID], [FullName], [Address], [City], [State], [Country], [Mobile], [EmailID]) 
VALUES (1, N'Rajesh Vyas', N'101, Riddhi Apartment, S. V. Road,', N'Mumbai', N'Maharashtra', N'India', N'56464654565', N'[email protected]')

INSERT [dbo].[tblEmployees] ([EmployeeID], [FullName], [Address], [City], [State], [Country], [Mobile], [EmailID]) 
VALUES (2, N'Kamlesh Purnia', N'202, Prolab Building, Near Mall Cinema, Goregoan-East', N'Mumbai', N'Maharashtra', N'India', N'998787875541', N'[email protected]')

INSERT [dbo].[tblEmployees] ([EmployeeID], [FullName], [Address], [City], [State], [Country], [Mobile], [EmailID]) 
VALUES (3, N'Ashish Kalla', N'2001, Oberoi Towerr, Near Oberoi Mall, Goregoan-East', N'Mumbai', N'Maharashtra', N'India', N'745564654522', N'[email protected]')

INSERT [dbo].[tblEmployees] ([EmployeeID], [FullName], [Address], [City], [State], [Country], [Mobile], [EmailID]) 
VALUES (4, N'Suhana Kalla', N'2501, Kankia Tower, Near Tipco, Malad-East,', N'Mumbai', N'Maharashtra', N'India', N'8978787877', N'[email protected]')

SET IDENTITY_INSERT [dbo].[tblEmployees] OFF

GO

How to set a database connection and fetch for operations?

Switch to Solution Explorer and in the root of the project folder select the file “appsettings.json”, this is the settings file of the application.

Update the connection string just below of AllowedHosts heading.

AppSettings.json file code

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=172.16.0.30;Initial Catalog=dbEmployee;User Id=dbdeveloper;Password=maha@123;TrustServerCertificate=true;MultipleActiveResultSets=true"
  }
}

Before proceeding to create the context class of the entity framework, install the following NuGet packages.

Microsoft.EntityFrameworkCore

Right-click on the project and select the Manage NuGet Packages option.

 NuGet Packages

Entity framework

Packages

Create Employee Model

Right-click on the project and click ADD -> NEW ITEM.

NEW ITEM

Class

Employee.cs file code

using System.ComponentModel.DataAnnotations;

namespace LearnBlazorServerApp
{
    public class Employee
    {
        [Key]
        public int EmployeeID { get; set; }

        public string FullName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Mobile { get; set; }
        public string EmailID { get; set; }
    }
}

Create Context Class

Right-click on Solution Explorer and select ADD -> New Item.

Add CLASS file and assign name: EmployeeContext.cs.

EmployeeContext.cs file code

using Microsoft.EntityFrameworkCore;

namespace LearnBlazorServerApp
{
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
        {
        }

        public DbSet<Employee> tblEmployees { get; set; } = null!;
    }
}

Now we are going to update the Program.cs file for database context class service.

First, add a reference to EntityFrameworkCore.

using Microsoft.EntityFrameworkCore;

builder.Services.AddDbContext<EmployeeContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Program.cs file code

using LearnBlazorServerApp;
using LearnBlazorServerApp.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

builder.Services.AddDbContext<EmployeeContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

Index Component: Employee Index Page.

Now we are going to create the List of Employees Razor component file EmployeeList.Razor, right-click click PAGES folder on Click on ADD -> Razor Component.

@page "/Employees"
@using LearnBlazorServerApp
@inject EmployeeContext context

<div class="container-fluid">
    <div class="card">
        <h3 class="card-title" style="margin-left:15px;">Manage Employee</h3>
        <a class="card-subtitle" style="margin-left:15px;" href="newemployee">New Employee</a>

        <div class="card-body">
            <table class="table table-bordered table-responsive table-striped">
                <thead>
                    <tr>
                        <td>ID</td>
                        <td>Fullname</td>
                        <td>City</td>
                        <td>State</td>
                        <td>Mobile</td>
                        <td>Email</td>
                        <td>Actions</td>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var eitem in EmpList)
                    {
                        <tr>
                            <td>@eitem.EmployeeID</td>
                            <td>@eitem.FullName</td>
                            <td>@eitem.City</td>
                            <td>@eitem.State</td>
                            <td>@eitem.Mobile</td>
                            <td>@eitem.EmailID</td>
                            <td>
                                <a class="btn btn-primary" href="EditEmployee/@eitem.EmployeeID">Edit</a>
                                <a class="btn btn-danger" href="DeleteEmployee/@eitem.EmployeeID">Delete</a>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
</div>
@code {
    List<LearnBlazorServerApp.Employee> EmpList;

    protected override void OnInitialized()
    {
        EmpList = context.tblEmployees.ToList();
    }
}

Output

Output

Add Country Column in Index Page View after State column.

<thead>
    <tr>
        <td>ID</td>
        <td>Fullname</td>
        <td>City</td>
        <td>State</td>
        <td>Country</td>
        <td>Mobile</td>
        <td>Email</td>
        <td>Actions</td>
    </tr>
</thead>
<tbody>
    @foreach (var eitem in EmpList)
    {
        <tr>
            <td>@eitem.EmployeeID</td>
            <td>@eitem.FullName</td>
            <td>@eitem.City</td>
            <td>@eitem.State</td>
            <td>@eitem.Country</td>
            <td>@eitem.Mobile</td>
            <td>@eitem.EmailID</td>
            <td>
                <a class="btn btn-primary" href="EditEmployee/@eitem.EmployeeID">Edit</a>
                <a class="btn btn-danger" href="DeleteEmployee/@eitem.EmployeeID">Delete</a>
            </td>
        </tr>
    }
</tbody>

NEW EMPLOYEE: To create an employee.

Now we are going to create a component for NEW EMPLOYEE, Right click on the PAGES folder and select ADD -> Razor Component.

NEW EMPLOYEE

@page "/newemployee"
@using LearnBlazorServerApp
@inject EmployeeContext context
@inject NavigationManager _NavigationManager

<div class="container-fluid">
    <div class="card">
        <h3 class="card-title" style="margin-left:15px;">New Employee</h3>

        <div class="card-body">
            <EditForm Model="@employee" OnValidSubmit="SubmitData" OnInvalidSubmit="CheckData">
                <DataAnnotationsValidator />
                <ValidationSummary />

                <div class="row">
                    <div class="col">
                        <label>Fullname</label>
                        <InputText class="form-control" @bind-Value="employee.FullName" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Address</label>
                        <InputText class="form-control" @bind-Value="employee.Address" />
                    </div>
                    <div class="col">
                        <label>City</label>
                        <InputText class="form-control" @bind-Value="employee.City" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>State</label>
                        <InputText class="form-control" @bind-Value="employee.State" />
                    </div>
                    <div class="col">
                        <label>Country</label>
                        <InputText class="form-control" @bind-Value="employee.Country" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Mobile</label>
                        <InputText class="form-control" @bind-Value="employee.Mobile" />
                    </div>
                    <div class="col">
                        <label>Email ID</label>
                        <InputText class="form-control" @bind-Value="employee.EmailID" />
                    </div>
                </div>

                <div class="form-group mt-3">
                    <button type="submit" class="btn btn-primary">Submit</button>
                    <a class="btn btn-info" href="employees">Back to List</a>
                </div>
            </EditForm>
        </div>
    </div>
</div>

@code {
    protected Employee employee = new();

    public void SubmitData()
    {
        context.tblEmployees.Add(employee);
        context.SaveChanges();
        _NavigationManager.NavigateTo("/employees");
    }

    public void CheckData()
    {
        // Optional: Implement validation or checks if needed
    }
}

Output

New Employee

After submitting the Redirect To Index Page (Razor Component).

Razor Component

Redirect to Other Component.

Add the following line to INJECT NavigationManager in the header section.

@inject NavigationManager _NavigationManager

@code {
    // Example of navigating or redirecting to another component
    private void NavigateToEmployees()
    {
        _NavigationManager.NavigateTo("/employees");
    }
}

Edit / Update Component for Employee data.

Now we are going to create a new component for EDIT/MODIFY/UPDATE employee details.

Right-click on the PAGES folder and select the ADDàRazor Component option.

ADD à Razor

EditEmployee.razor file code

@* To receive the parameter in INT datatype property name is id *@
@page "/editemployee/{id:int}"
@using LearnBlazorServerApp
@inject EmployeeContext context
@inject NavigationManager _NavigationManager

<div class="container-fluid">
    <div class="card">
        <h3 class="card-title" style="margin-left:15px;">Edit Employee</h3>

        <div class="card-body">
            <EditForm Model="@employee" OnValidSubmit="SubmitData" OnInvalidSubmit="CheckData">
                <DataAnnotationsValidator />
                <ValidationSummary />

                <div class="row">
                    <div class="col">
                        <label>Fullname</label>
                        <InputText class="form-control" @bind-Value="employee.FullName" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Address</label>
                        <InputText class="form-control" @bind-Value="employee.Address" />
                    </div>
                    <div class="col">
                        <label>City</label>
                        <InputText class="form-control" @bind-Value="employee.City" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>State</label>
                        <InputText class="form-control" @bind-Value="employee.State" />
                    </div>
                    <div class="col">
                        <label>Country</label>
                        <InputText class="form-control" @bind-Value="employee.Country" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Mobile</label>
                        <InputText class="form-control" @bind-Value="employee.Mobile" />
                    </div>
                    <div class="col">
                        <label>Email ID</label>
                        <InputText class="form-control" @bind-Value="employee.EmailID" />
                    </div>
                </div>

                <div class="form-group mt-3">
                    <button type="submit" class="btn btn-primary">Submit</button>
                    <a class="btn btn-info" href="employees">Back to List</a>
                </div>
            </EditForm>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public int id { get; set; }

    protected Employee employee = new();

    protected override void OnParametersSet()
    {
        employee = context.tblEmployees.FirstOrDefault(a => a.EmployeeID == id);
    }

    public void SubmitData()
    {
        context.SaveChanges();
        _NavigationManager.NavigateTo("/employees");
    }

    public void CheckData()
    {
        // Optional: Implement validation or checks if needed
    }
}

Now run the Employees component.

Employee Index Page

Employee Index Page

After selecting the first item for edit from the INDEX page.

Edit from

Changed three things.

  1. Fullname
  2. Address
  3. EmailID

Edit employee

On submission redirect to the Index page and check your changes have been implemented.

Submission redirect

Delete / Remove Component for Employee data

Now we are going to create a new component for DELETE/REMOVE employee details.

Right-click on the PAGES folder and select the ADDàRazor Component option.

 PAGES folder

DeleteEmployee.razor file code

@* To receive the parameter in INT datatype property name is id *@
@page "/deleteemployee/{id:int}"
@using LearnBlazorServerApp
@inject EmployeeContext context
@inject NavigationManager _NavigationManager

<div class="container-fluid">
    <div class="card">
        <h3 class="card-title" style="margin-left:15px;">Delete Employee</h3>

        <div class="card-body">
            <EditForm Model="@employee" OnValidSubmit="SubmitData">
                <DataAnnotationsValidator />
                <ValidationSummary />

                <div class="row">
                    <div class="col">
                        <label>Fullname</label>
                        <InputText class="form-control" @bind-Value="employee.FullName" disabled="disabled" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Address</label>
                        <InputText class="form-control" @bind-Value="employee.Address" disabled="disabled" />
                    </div>
                    <div class="col">
                        <label>City</label>
                        <InputText class="form-control" @bind-Value="employee.City" disabled="disabled" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>State</label>
                        <InputText class="form-control" @bind-Value="employee.State" disabled="disabled" />
                    </div>
                    <div class="col">
                        <label>Country</label>
                        <InputText class="form-control" @bind-Value="employee.Country" disabled="disabled" />
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <label>Mobile</label>
                        <InputText class="form-control" @bind-Value="employee.Mobile" disabled="disabled" />
                    </div>
                    <div class="col">
                        <label>Email ID</label>
                        <InputText class="form-control" @bind-Value="employee.EmailID" disabled="disabled" />
                    </div>
                </div>

                <div class="form-group mt-3">
                    <button type="submit" class="btn btn-danger">Submit</button>
                    <a class="btn btn-info" href="employees">Back to List</a>
                </div>
            </EditForm>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public int id { get; set; }

    protected Employee employee = new();

    protected override void OnParametersSet()
    {
        employee = context.tblEmployees.FirstOrDefault(a => a.EmployeeID == id);
    }

    public void SubmitData()
    {
        context.tblEmployees.Remove(employee);
        context.SaveChanges();
        _NavigationManager.NavigateTo("/employees");
    }

    public void CheckData()
    {
        // Optional: Implement validation or checks if needed
    }
}

Now run the Employees component.

Employee Index Page

Employee Index Page

After the selection first item for edit from the INDEX page.

Delete view all textbox control disabled.

Textbox control

After clicking on the submit button, You can see in the following screen the first record “Manoharlal” was deleted successfully.

Deleted

Now, we have updated the left menu with the EMPLOYEE option.

Switch to the SHARED folder and select NAVMENU.RAZOR file.

Add the following code just below the FETCH DATA div tags.

<div class="nav-item px-3">
    <NavLink class="nav-link" href="employees">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Employee
    </NavLink>
</div>

Please implement this article step by step so you can easily achieve CRUD activities.

In the next article, you will learn about Services, Validation, and binding with other form controls like (Dropdown, Radio button, and Checkbox).

Happy Coding!


Similar Articles