Skip to main content

.NET5 Blazor Server CRUD Operation Using Entity Framework Core

In this article, we are going to implement CRUD operations in .Net5 Blazor Server application.

Blazor Server:

Blazor Server is a single-page application. At the server, a pre-rendered HTML output of the page will be delivered to the user browsers. Any UI update, event handling, javascript calls will carry over by a SignalR connection to the server. So application updates or depends on the continuous connection of the SignalR.

So Blazor Server is a single-page application that will be made of c#. Since the blazor server only outputs the pre-rendered HTML to the client, so there is no c# code downloading into user browsers like in Blazor Webassembly(c# code downloaded and runs in browser for blazor webassembly application).

Role Of SignalR Connection:


A Blazor Server application works over a SignalR connection. A Blazor Server application creates a UI State memory at the server which will be interacted by the SignalR connections. If a SignalR connection got interrupted, then the client tries to maintain the same state of the application by initiating a new SignalR connection and uses the existing UI state memory at the server. App routing changes, event changes, data changes everything will be carried out by the SignalR connection without any page reloads.

Each browser screen or browser tab has its own SignalR connection channels and UI states at the application. So each browser screen or browser tab acts as an individual user request.

Blazor Components:

Blazor Server application built on top of the 'Blazor Components'. A blazor component file will be created like 'Example.razor', the file extension is '.razor'. A blazor component file consists of both c# and razor syntaxes. Blazor component also provides an option to split the files like 'Example.razor'(contains all razor code) and 'Example.razor.cs'(contains all c# code).

Create A .Net5 Blazor Server Application:

Let's start our learning journey by creating a .Net5 Blazor Server Application sample project.

Visual Studio users can easily create .Net5 Blazor Server Application. On creating application visual studio UI shows different application template options in that we have to select 'Blazor Server App'.

Here for this demo, I'm going to use Visual Studio Code editor and  .NET CLI commands. Run the below .NET CLI command to create Blazor Server App.
CLI Command To Blazor Server Application:
dotnet new blazorserver -n your_project_name
After creating an application, few things we need to aware of about the project:

Register RazorPages And Blazor Server Service- In the 'Startup.cs' file registered with 'AddRazorPages' and 'AddServerSideBlazor' services to gain dependency injection benefits.

Endpoint Routing Middleware - In the 'Starup.cs' file configured endpoint middleware with 'MapBlazorHub'(for SignalR routing) and 'MapFallbackToPage' (for Blazor Server routing).

Pages/_Host.cshtml - It is the entry file for any of our first requests to the server. It renders the default blazor component like 'App.razor'.

App.razor -  This is then the entry Blazor component. It contains a default blazor router component like 'Router'. The 'Router' component handles the user request and loads the appropriate Blazor Page components.

MainLayout.razor and NavMenu.razor - Default layout blazor component.

Pages Folder - Area to create blazor components

wwwroot Folder - Area to store all static files like js, css, images, etc.

Entity Framework Core:

Entity Framework Core is an Object/Relational Mapping(ORM) framework. EF Core makes database communication more fluent and easy. 
EF Core supports:
  • Database First Approach.
  • Code First Approach.
Code First Approach means first we will create c# POCO classes and then create the database tables. Code First Approach has one more sub-category like 'Code First With Existing Database'. So the 'Code First With Existing Database' can work with the already created tables in the database which is an ideal choice for real-time development. Our demo will be implemented using 'Code First With Existing Database'.

Install EF Core Nuget:

Now install ef core and SQL ef core extension Nuget package into our application.
Package Manager(Visual Studio):
Install-Package Microsoft.EntityFrameworkCore -Version 5.0.6
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.6
CLI Commands(Visual Studio Code):
dotnet add package Microsoft.EntityFrameworkCore --version 5.0.6
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 5.0.6

Sample SQL Script:

To follow the demo, run the SQL script to generate the table.
CREATE TABLE [dbo].[Gadgets](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ProductName] [varchar](max) NULL,
	[Brand] [varchar](max) NULL,
	[Cost] [decimal](18, 0) NOT NULL,
	[ImageName] [varchar](1024) NULL,
	[Type] [varchar](128) NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Setup Entity Framework Core DbContext:

First, let's create POCO class that represents our table. So let's create a new folder 'Entities' inside of the Data Folder, then inside of the 'Entities' folder creates our POCO class.
Data/Entities/Gadgets.cs:
namespace Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities
{
    public class Gadgets
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public string Brand { get; set; }
        public decimal Cost { get; set; }
        public string Type { get; set; }
    }
}
In EF Core DbContext is like a database that manages all POCO classes(classes represent tables). Inside the 'Data' folder create a context class.
Data/MyWorldDbContext.cs:
using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace Dotnet5.BlazorServer.CRUD.EFCore.Data
{
    public class MyWorldDbContext : DbContext
    {
        public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options) : base(options)
        {

        }
        public DbSet<Gadgets> Gadgets { get; set; }
    }
}
Add database connection string into 'appsetting.Development.json'.
appsetings.Development.json:
"ConnectionStrings":{
    "MyWorldDbConnection":"your_connection"
}
Register 'MyWorlDbContext' into the dependency services.
services.AddDbContext<MyWorldDbContext>(options =>
{
	options.UseSqlServer(Configuration.GetConnectionString("MyWorldDbConnection"));
});

Read Operation:

First, let's register some namespaces into the '_Imports.razor' file.
_Imports.razor:
@using Dotnet5.BlazorServer.CRUD.EFCore.Data
@using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities
@using Microsoft.EntityFrameworkCore
For our demo, we will use the existing blazor page component that is 'Pages/Index.razor'. So let's start working on implementing 'Read Operation.
Pages/Index.razor:(HTML Part)
@page "/"
@inject MyWorldDbContext _myWorldDbContext;

<div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col">Id</th>
                <th scope="col">Product Name</th>
                <th scope="col">Brand</th>
                <th scope="col">Cost</th>
                <th scope="col">Type</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <th scope="row">@item.Id</th>
                    <td>@item.ProductName</td>
                    <td>@item.Brand</td>
                    <td>@item.Cost</td>
                    <td>@item.Type</td>
                </tr>
            }
        </tbody>
    </table>
</div>
  • (Line: 1) Routing to a blazor component should be defined using the '@page' directive.
  • (Line: 2) Injected our database context using the '@Inject' directive.
  • (Line: 16-25) The 'AllGadgets' is a c# property that contains a collection. Here binding the data to the bootstrap table.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }
}
  • (Line: 1) The entire c# code must be encapsulated inside of the '@code' directive.
  • (Line: 2)  Declared and initialized a collection property like 'AllGadgets'.
  • By default, it always recommended to use asynchronous calls to scale up the application. So for a method to we must use the 'async' keyword and output must be either 'Task' or 'Task<T>' and inside the method, every asynchronous job must be prefixed with the 'await' keyword.
  • (Line: 4-7) The 'OnInitializedAsync' is the default life cycle method of Blazor Server. Here fetching all data from the database and assigning to the 'AllGadgets' property.

Create Operation:

Bootstrap modal will be used for 'Create Operation'. So first let's add the Bootstrap 'js' and JQuery 'js' into the '_Host.cshtml'.
Pages/_Host.cshtml:(Above the closing body tag)
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
In Blazor c# code can invoke the javascript code that is called 'Blazor JavaScript Interoperability'. Now we have to write some javascript code to open and close the Bootstrap Modal. That javascript code will be called from the c# code in upcoming steps. So in 'wwwroot' folder add a new folder like 'js' and then add a new file like 'app.js'.
wwwroot/js/app.js:
window.global = {
  openModal: function (modalId) {
    modalId = "#" + modalId;
    $(modalId).modal("show");
  },
  closeModal: function (modalId) {
    modalId = "#" + modalId;
    $(modalId).modal("hide");
  },
};
  • Here written javascript code to open the bootstrap modal by its HTML id value.
Now, let's import our 'app.js' file onto the '_Host.cshtml' file.
Pages/_Host.csthml:
<script src="js/app.js"></script>
Now let's add our 'Create Operation' changes onto the 'Index.razor' component.
Index.razor:(HTML Part)
@page "/"
@inject MyWorldDbContext _myWorldDbContext;
@inject IJSRuntime _jsRuntime;
<!-- Some code hidden for display purpose -->
<button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(0))'>Add</button>
<div>
    <table class="table table-bordered">
        
    </table>
</div>


<div class="modal fade" id="createOrupdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@CreateOrUpdateTitle</h5>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="txtProductName" class="form-label">Product Name</label>
                    <input @bind="FormPayload.ProductName" type="text" class="form-control" id="txtProductName">
                </div>
                <div class="mb-3">
                    <label for="txtBrand" class="form-label">Brand</label>
                    <input @bind="FormPayload.Brand" type="text" class="form-control" id="txtBrand">
                </div>
                <div class="mb-3">
                    <label for="txtCost" class="form-label">Cost</label>
                    <input @bind="FormPayload.Cost" type="text" class="form-control" id="txtCost">
                </div>
                <div class="mb-3">
                    <label for="txtType" class="form-label">Type</label>
                    <input @bind="FormPayload.Type" type="text" class="form-control" id="txtType">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @onclick='@(e => CloseModal("global.closeModal", "createOrupdateModal"))'
                    data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" @onclick="Save">Save</button>
            </div>
        </div>
    </div>
</div>
  • (Line: 3) Injected 'IJSRuntime' that helps to invoke the javascript code from the c# code.
  • (Line: 5) Created 'Add' button. Here button registered with c# method to  'onclick' event. To use c# method that has parameters we need to call like delegate(eg: e => method_name(param1)) in the HTML.
  • (Line: 13-44) Add the Bootstrap Modal Html. Our Bootstrap Modal popup furnished with all HTML input fields for creating a new record. To achieve a 2-way binding input HTML field must be decorated with the '@bind' directive.
  • (Line: 17) Rendering popup title dynamically using the property 'CreateOrUpdateTitle'. So that same popup can be used for Edit operation as well in the coming steps.
  • (Line: 38-39) Added the popup close button and its click event registered with a method like 'CloseModal'.
  • (Line: 40) Added the popup save button and its click event registered with a method like 'Save'.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
            await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
        }
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }
}
  • (Line: 5) Added property 'FormPayload' of type 'Gadgets'. This 'FormPayload' property will be utilized by the input fields of our Bootstrap Modal for 2-way binding.
  • (Line: 6) Added the property 'CreateOrUpdateTitle' to dynamically add the title to Bootstrap Modal.
  • (Line: 12-20) Method to open the bootstrap modal on clicking the 'Add' button.
  • (Line: 16) Defining the title for our bootstrap modal.
  • (Line: 17) Since it creates a new record, so will assign an empty memory to our 'FormPayload' property.
  • (Line: 18) Using 'JSRuntime' invoking the javascript method. So for the method 'InvokeVoidAsync', the first parameter will be the javascript function name and the second parameter will be the input parameters array for the javascript method.
  • (Line: 22-25) Method to close the bootstrap modal. Here it was written in a generic way so any number of popups can use this method as a close event.
  • (Line: 27-36) The 'Save' method used to create new records into the database.
  • (Line: 29) Checking the 'Id' value because 'Save' method we will use for both 'Create' and 'Update' operations. If the 'Id' value is '0' then it is a 'Create' operation.
  • (Line: 31-32) Saving the new record into the database.
  • (Line: 34) Added the newly created or update record into the 'AllGadgets' collection. So our table gets updated with newly created or updated data.
  • (Line: 35) Finally closing the modal.
step1:

step2:

step3:

Update Operation:

Now let's implement our logic to fulfill our 'Update Operation'.
Pages/Index.razor:(HTML Part)
<!-- Code hidden for display purpose -->
<div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <td>
                        <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
  • (Line: 6) Created a new table column like 'Actions'.
  • (Line: 14) Added the edit button for each record in the table. So here we will use the same methods that are used in 'Create Operation'.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
        }
        else
        {
            CreateOrUpdateTitle = "Update The Gadget";
            FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync();
        }
        await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        else
        {
            _myWorldDbContext.Update(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
            AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }
}
  • (Line: 21-22) Updating the 'CreateOrUpdateTitle' property as per the operation type. Updating the 'FormPayload' with data fetched from the database with help of the 'gadgetId' value.
  • (Line: 41-42) Updating the Dbcontext with our record to be updated.
  • (Line: 43) Remove the record that is updated from the old collection 'AllGadgets'.
step1:

step2:

step3:

Delete Operation:

Now let's implement our logic for 'Delete Operation'.
Pages/Index.razor:(HTML Part)
<!-- Some code hidden for display purpose -->
<div>
    <table class="table table-bordered">
        
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <td>
                        <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button> |
                        <button class="btn btn-danger"
                        @onclick='@(e => OpenDeleteConfrimationModal(item.Id))'>Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

<div class="modal fade" id="deleteGadgetModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
                <h4>Are you sure, you want to delete?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary"
                    @onclick='@(e => CloseModal("global.closeModal", "deleteGadgetModal"))'
                    data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger" @onclick='ConfirmDelete'>Confirm Delete</button>
            </div>
        </div>
    </div>
</div>
  • (Line: 11-12) Add the new button like 'Delete'. Click event registered with method 'OpenDeleteConfirmationModal'.
  • (Line: 20-35) Add a new bootstrap modal for the delete confirmation.
  • (Line: 31) Delete button added and registered with 'ConfirmDelete' method.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;

    public int GadgetIdToRemove = 0;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
        }
        else
        {
            CreateOrUpdateTitle = "Update The Gadget";
            FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync();
        }
        await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        else
        {
            _myWorldDbContext.Update(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
            AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }

    public async Task OpenDeleteConfrimationModal(int gadgetId)
    {
        GadgetIdToRemove = gadgetId;
        await _jsRuntime.InvokeVoidAsync("global.openModal", "deleteGadgetModal");
    }

    public async Task ConfirmDelete()
    {
        var gadtetToDelete = await _myWorldDbContext.Gadgets.Where(_ => _.Id == GadgetIdToRemove).FirstOrDefaultAsync();
        _myWorldDbContext.Gadgets.Remove(gadtetToDelete);
        await _myWorldDbContext.SaveChangesAsync();
         AllGadgets = AllGadgets.Where(_ => _.Id != GadgetIdToRemove).ToList();
        await CloseModal("global.closeModal", "deleteGadgetModal");
    }
}
  • (Line: 8) Added variable 'GadgetIdToRemove' to store the 'Id' value of the record that needs to be deleted.
  • (Line: 51-55) Opens the delete confirmation popup.
  • (Line: 57-64) The 'ConfirmDelete' method to delete the record from the database.
So that's all about the CRUD operation in .Net5 Blazor Server application.

Video Session:

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on .Net5 Blazor Server CRUD operation with the entity framework. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. don't you think it might be good somehow to allow "printing" ?
    I just can't do that because of the "trimmed " source code in those magic code boxes
    which inhibit seeing the full lenght of the code lines

    ReplyDelete

Post a Comment

Popular posts from this blog

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http

GraphQL API Integration In Asp.Net Core Application

Introduction: GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data. How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions. HTTP-POST is the only Http verb recommended by the GraphQL. The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API: The main building blocks of GraphQL API is Schemas and Types.  A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc. T