My Blog List

Sunday, September 27, 2020

Razor Page CRUD in ASP.NET Core 3.1 with jQuery AJAX | Visual Studio 2019 for Mac | CRUD on Single Page | MySQL

In this tutorial, we will learn a clean and simple way to implement Razor Page CRUD in Asp.Net Core with jQuery Ajax and Bootstrap Modal. This is the Entity Management Set of CRUD operations which doesn't reload the  Pages, we can call it Single Page Application.




Table of Contents:

  1. Scope
  2. The Architecture
  3. Getting Started with Razor Page CRUD in ASP.NET Core
    • Setting up the Project
    • Setting up the Core Layer
    • Setting up the Infrastructure Layer
    • Setting up the Asp.Net Core Project
    • Rendering Razor Partial View to String

Scope 

There are the things we will be implementing in our CRUD Application. This will be an Employee Management System.

  • Data Annotations for Validations
  • jQuery Validations and Unobstructive Validations - Client Side Validations
  • Bootstrap Modal
  • Dyanamic Loading of Partial Views via Ajax Calls
  • Repository Pattern with Unit of. Work
  • Onion Architecture Solutions
  • jQuery Datatables

The Architecture

To keep things simple and clean we will be using onion architecture with inverted dependencies.

We will create three layers in this project repectively Web, Core and Infrastructure.

Getting Started with Razor Page CRUD in Asp.Net Core 3.1

Let's create the required projects, here I am creating the Web project first using Visual Studio 2019

for Mac.

Setting up the Projects



Setting up the Core Layer

Let's add a new project withing the same solution and name it Core. This will be created as .Net Core Library 3.1


Let's add two folders Entities and Interfaces in the Core Project. And under the Entities folder, create a new class and name it Employee

To follow the Repository pattern, we will add a new interface and name it IGenericRepositoryAsync under the Interfaces folder in Core Proejct Layer.

So we have a generic repository. now to use this generic interface for a specific entity like an employee along with extra methods, we will add a new interface and name it IEmployeeRepositoryAsync

Let's add the unit of work



We have completed everything for the Core Project Layer, now let's move to create Infrastructure Project Layer as we did for the Core Project layer.

Setting up the Infrastructure Project Layer

Let's install the below-required packages for Infrastructure Layer



Now that you have Entity Framework Core installed at the Infrastructure Layer, let’s add the ApplicationDbContext in-order to access the database. (We will be setting the connection string to the database later in this article at the Web Layer.)

Create a new Folder in the Infrastructure Layer and name it Data. Here add a new Class and name it ApplicationDbContext.cs



Add a new folder in the Infrastructure layer and name it Repositories. Here add a new class, GenericRepositoryAsync.cs



As you can see from the above, almost all the CRUD operations ever needed for any entity is covered. T could be any class and you already have an entire class that could Perform Create, Read, Update and Delete Operations on the T Entity. But also see that we are not saving anything directly to the database via the Repository Implementation. Rather we will have a separate class that is responsible for Committing changes to the database. You should have heard about Unit Of Work, yeah?

Create another new class and name it UnitOfWork.cs in the Infrastructure layer.



Let's add the last implementation which is responsible for performing the CRUD operations specific to Employee Entity.



Setting up the Asp.Net Core Project


Let's install the below-required packages for the Web project layer.



With that done, open up the Startup.cs. Here we will have to add the services/dependencies to our ASP.NET Core Container. Navigate to the ConfigureServices method and add the following. Note that you would have to fix the reference warnings that may occur.



We should add the connectionString in our appsettings.json file... So let's move to add ConnectionStrings



Now we need to add the migrations. if you want to know how to add Migrations so click here to Add Migrations

Let's install the jQuery Datatables into our Web project and add the reference for DataTables in _Layout.cshtml file as below.



Since we are already here, let’s also add the skeleton of the Bootstrap Modal that we are going to use further in the article. Above the footer tag, add the HTML for the Modal. Note that the Modal Body is empty. This is because we will be filling it dynamically via jQuery AJAX with Razor Partial Views.



There is already a site.js file under the wwwroot/js folder. So let's add the below code. Here we'll add the 3 functions which will be required for CRUD operations and it's the important part of our project which allows us not to reload the pages.
GetAll() - Loads all the Employees from the database to the jQuery DataTables.
CreateOrEdit() - This functions do the Create or Edit an employee.
Delete() - It deletes an employee from the database.

Now the missing pieces to the puzzle are as follows:

1. Razor Partial View to Hold the jQuery Datatable.
2. Razor Partial View to Add / Edit Customer.
3. A way to convert Razor Views to String, so that jQuery AJAX can fetch this string and simply overwrite the existing div / DOM object on the HTML. (This was particularly tough to figure out.)
4. And finally, our C# Handler methods that will return the partial views as requested by the AJAX calls.

Let’s start with the _ViewAll.cshtml. This will hold the HTML table definition and also the script needed to activate jQuery Datatable. Under the Pages folder in the Web Project, Create a new Razor View (Empty) and name it _ViewAll.cshtml.

Next, Let’s create the Form, CreateOEdit that will have all the fields we require. This is again a straight forward piece of code snippet. Create a new Razor Page View (Empty) and name it _CreateOrEdit.cshtml and add in the following.



Now we required the partial views, so let's add the following code in our existing Index.cshtml file



Rendering Razor Partial View to String


Now, the question is, We have Razor Partial Views and AJAX, how do you convert Razor Partial Views to Strings / HTML. The answer is to create a service that can do so. In the Web Project add a new Folder and name it Services. And in it, create a new class and name it RazorRenderService.cs




Let's add the below services into the Startup.cs as in ConfigureServices method.



This is the final part of the puzzle. The actual Index.cs. Open it up and add the following.



Now you can build your all projects and run the application... :)

 
Please comment if you face any issue in code.

You can download the Source Code from GitHub

Read my previous blog on ASP.NET Core 3.1 MVC CRUD Operations

Below is a small video of my running application...




Friday, September 25, 2020

ASP.NET Core 3.1 MVC | EntityFrameworkCore | Visual Studio 2019 for Mac | CRUD Operations | MySQL

Today we will create an asp.net core MVC application using EntityFramework and MySQL Database with Visual Studio 2019 for Mac.

This is a simple CRUD operation for an Employe using ASP.NET Core 3.1 and EntityFrameworkCore


Prerequisites:
  1. Visual Studio 2019 IDE for Mac
  2. Make sure you are running the latest .Net core 3.1
  3. Install the latest DOTNET and EF CLI using this command: dotnet tool install --global dotnet ef
  4. MySQL database should be installed on your Mac

Getting Started:

         Open the Visual Studio 2019 for Mac and Create a New Project as below

    
     Please select the .Net Core 3.1  as below


        I created a new project with the Name, "DotNetCore" and below is the Solution structure which
        is created by VS2019.



        Let's install the few mandatory nuget packages as below

                        1. Microsoft.EntityFrameworkCore
                        2. Microsoft.EntityFrameworkCore.Design
                        3. Microsoft.EntityFrameworkCore.Tools
                        4. MySql.Data
                        5. MySql.Data.EntityFrameworkCore

        Now let's add a New Class name "DotNetCoreDbContext" under the Models folder by 
right-clicking
        and select Add New Class.


        Now let's write the code for this class.
        We have to inherit our class from the DbContext class by using Microsoft.EntityFrameworkCore
        
        Now let's add a New Class name "Employee" under the Models folder.
        
        
        Now add our class into DotNetCoreDbContext as below
        
        Now we need to write code for ConnectionStrings in appsettings.json file
        and modify the Startup.cs file as below
        
        Next step to add the Migration to create the Database in MySql

        Run below command w.r.t your project folder path on Terminal
        
        To Add-Migration:
        dotnet ef migrations add InitialCreate

        To Update-Database
        dotnet ef database update

        To Remove-Migration:
        dotnet ef migrations remove

        After adding the Migration, we can see our database has been created into the MySql database

        We can see our created database dotnetcore including the Employees table.


           Now let's add the controller name "EmployeeController" using Scaffolding as below
        
            

        We will use the same action for Create and Edit an Employee.
        Let's write the code for AddOrEdit action into EmployeeController
        
        Now let's add the view page for AddOrEdit action under the Views/Employee folder

        
        We have written the code to create and edit an employee, added the view page also.
        Now let's build our solution and run the application.
        Let's create 3-4 employees by entering the required fields as below

        Let's write some action methods to Index, Details, and Delete an employee as well

        Below are the screenshots for Index, Details, and Delete action methods

        https://localhost:5001/Employee/Index


        https://localhost:5001/Employee/Details/1



        Now let's delete the Harshit Kumar record... it will show an alert popup message as below


        Harshit Kumar record has been deleted from the database as we can see the below
    
        

           Below is the Employee table screenshot



        I hope it will help you :)
        
        Please comment if you face any issue regarding the same...

        You can download the source code from GitHub by click on the below link

Below is the video of my running application: