All You Need To Know About Blazor App And Creating ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API

Introduction
 
Blazor has two kinds of Application development on is Blazor Client app which is in preview now and also Blazor Server app. Blazor Client app runs in WebAssembly, Blazor Server app runs using SignalR. Blazor apps can be created using C#, Razor, and HTML instead of JavaScript Blazor WebAssembly Works in all modern web browsers also in mobile browsers. The main advantage we have in Blazor is C# code files and Razor files are compiled into .NET assemblies. Blazor has reusable components, Blazor Component can be as a page, Dialog or Entry Form, Blazor also used to create Single Page Applications. Blazor is used to create two kinds of applications one is Blazor Client-Side App and another one is Blazor Server Side APP.here we will see some more details on
 

Blazor Client App

  • Blazor Client Side is still in preview.
  • Blazor Client side uses Web Assembly
  • In Blazor Client Side all the.Net dll’s will be downloaded to the browser. The download size might be bigger and might be some time delay in loading due to all downloads happen in client browser.
  • No need of server-side dependency for the Blazor Client-side application.
  • All similer kind of JavaScript coding can be done in the Blazor Client app and it’s not really needed to use JavaScript Interop.
  • It can be deployed as Static site which means it supports offline as well.
  • Debugging is more complicated than Blazor Server side.
  • In client-side leaking of database connectivity and also all the application code will be on client-side and the security level is not very good.

Blazor Server App

  • All the Component Process will be happening in the Server.
  • Blazor Server uses SignlR Connection to connect from the webserver to browsers.
  • In client side leaking of database connectivity is not happen as all will be happen in Server.
  • All the form connection will be happening on the server side and no DLL's download to the client side.As all the dll’s will be in web server.
  • Small download size and faster loading time than the Blazor Client App.
  • We can use .Net core in the Blazor server side.
  • Debugging is great in Blazor Server Side.
  • Runs in any web browser as no need for WebAssemble.
  • Each browser session is open with a SignalR connection.
Prerequisites
Step 1 - Create a database and a table
 
We will be using our SQL Server database for our WEB API and EF. First, we create a database named CustDB and a table as CustDB. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project. 
  1. USE MASTER         
  2. GO         
  3.          
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB         
  5. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'CustDB' )         
  6. DROP DATABASE CustDB         
  7. GO         
  8.          
  9. CREATE DATABASE CustDB         
  10. GO         
  11.          
  12. USE CustDB         
  13. GO         
  14.          
  15. -- 1) //////////// Customer Masters      
  16.   
  17.   
  18. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'CustomerMaster' )         
  19. DROP TABLE CustomerMaster         
  20. GO         
  21.          
  22. CREATE TABLE [dbo].[CustomerMaster](         
  23.         [CustCd] [varchar](20) NOT NULL ,           
  24.         [CustName] [varchar](100) NOT NULL,            
  25.         [Email]  [nvarchar](100) NOT NULL,          
  26.         [PhoneNo] [varchar](100) NOT NULL,             
  27.         [InsertBy] [varchar](100) NOT NULL,     
  28.         PRIMARY KEY (CustCd)    
  29. )         
  30.          
  31. -- insert sample data to Student Master table         
  32. INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)         
  33.      VALUES ('C001','ACompany','acompany@gmail.com','01000007860','Shanun')         
  34.          
  35. INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)         
  36.      VALUES ('C002','BCompany','bcompany@gmail.com','0100000001','Afraz')    
  37.   
  38. INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)         
  39.      VALUES ('C003','CCompany','ccompany@gmail.com','01000000002','Afreen')    
  40.   
  41. INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)         
  42.      VALUES ('C004','DCompany','dcompany@gmail.com','01000001004','Asha')    
  43.               
  44.      select * from CustomerMaster  
Step 2 - Create ASP.NET Core Blazor Server Application
 
After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project. 
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Click Create a new project to create our ASP.NET Core Blazor Application.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Select Blazor App and click Next button
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Select your project folder and Enter your Project name and then click Create button.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
After creating ASP.NET Core Blazor Server Application, wait for a few seconds. You will see the below structure in solution explorer.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
In the Data folder we can add all our Model, DBContext Class, Services and Controller, we will see that in this article.
 
In the Pages folder we can add all our component files.component file all should have the .razor extension with the file name.
 
In the Shared folder we can add all left menu form NavMenu.razor file and change the main content from the MainLayout.razor file.
 
In the _Imports.razor file we can see all set of imports has been added inorder to used in all component pages.
 
In the App.razor file we will add our main component to be displayed by default when run in browser.
 
Appsertings.json can be used to add the connection string.
 
Startup.cs file is important file where we add all our endpoints example like Controller end points, HTTP Client,add services and dbcontext to be used in startup Configuration method.
 

Run to test the application

 
When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 

Debug in component

 
The big advantage of Blazor is as we can use our C# code in razor and also keep the breakpoint in the code part. In the browser we can debug and check for all our business logic is working properly and to trace any kind error easily with the breakpoint.
 
For this we take our existing Counter component page.
 
This is the actual code of our Counter page as in the counter we can see there is button and in button click called the method to perform the increment.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
We add one more button and in button click event we call the method and bind the name in our component page.
 
In html design part we add the below code.
  1. <h1>My Blozor Code part</h1>  
  2.     My Name is : @myName   <br />  
  3.  <button @onclick="ClickMe">Click Me</button>  
Note that : all the C# code part and functions can be written under the @code {} part.
 
We add the method ClickMe and declare property to bind the name inside the @Code part
  1. [Parameter]  
  2.     public string myName { getset; }  
  3. private void ClickMe()  
  4.     {  
  5.         myName="Shanu";  
  6.     }  
The complete Coutner Component page code will be like this.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Now lets add the break point in our ClickMe method,
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Run the program and open the counter page.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API
 
We can see as when we click on the Click Me button we can debug and check for the value from the breakpoint we placed.
 
Now lets see on performing CRUD operation using EF and Web API in Bloazor.
 
Step 3 - Using Entity Framework
 
To use the Entity Framework in our Blazor application we need to install the below packages
 
Install the Packages
 
Microsoft.EntityFrameworkCore.SqlServer - For using EF and SQL Server
Microsoft.EntityFrameworkCore.Tools - For using EF and SQL Server
Microsoft.AspNetCore.Blazor.HTTTPClient - For communicating WEB API from our Blazor Component.
 
First we will add the Microsoft.EntityFrameworkCore.SqlServer ,For this right click on the project and click on Manage NuGet Packages.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Search for all the three packages and install all the needed packages like the below image.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 

Add DB Connection string

 
Open the appsetting file and add the connection string like below image.
  1. "ConnectionStrings": {  
  2.     "DefaultConnection""Server= DBServerName;Database=CustDB;user id= SQLID;-password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true"  
  3. },  
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 

Create Model Class

 
Next, we need to create the Model class with same as our SQL Table name and also define the property fields similar to our SQL filed name as below.
 
Right Click the Data Folder and create new class file as “CustomerMaster.cs”
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
In the class, we add the property field name the same as our table column names like the below code.
  1. [Key]  
  2.         public string CustCd { getset; }  
  3.         public string CustName { getset; }  
  4.         public string Email { getset; }  
  5.         public string PhoneNo { getset; }  
  6.        public string InsertBy { getset; }  

Create dbConext Class

 
Next, we need to create the dbContext class. Right Click the Data Folder and create a new class file as “SqlDbContext.cs”
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
We add the below code in the DbContext class as below in order to add the SQLContext and add the DBset for our CustomerMaster Model.
  1. public class SqlDbContext:DbContext  
  2.     {  
  3.         public SqlDbContext(DbContextOptions<SqlDbContext> options)  
  4.            : base(options)  
  5.         {  
  6.         }   
  7.         public DbSet<BlazorCrudA1.Data.CustomerMaster> CustomerMaster { get; set; }  
  8.     }  

Adding DbContext in Startup

 
Adding the DbContext in Startup.cs file ConfigureServices method as below code and also we give the connection string which we used to connect to SQLServer and DB.
  1. services.AddDbContext<SqlDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
Note that in the ConfigureServices method we can also see as the weatherforecast service has been added.if we create an new service then we need to add the service in like below code in ConfigureServices method.
  1. services.AddSingleton<WeatherForecastService>();  

Creating Web API for CRUD operation

 
To create our WEB API Controller, right-click Controllers folder. Click Add New Controller.
 
Here we will be using the Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework and click Add button.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Select our Model class and DBContext class and click Add button.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we no need to write any code in Web API now as we have used the Scaffold method for all the actions and methods add with code.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get /api/CustomerMasters/

Run the program and paste API path to test our output.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
If you see this error means then we need to add the endpoints of controller in the Startup.cs file Configure method.
 
Add the below code in the Configure method in Startup.cs file
  1. endpoints.MapControllers();  
we add inside the UseEndpoints like below code in Configure method.
  1. app.UseEndpoints(endpoints =>  
  2.             {  
  3.                 endpoints.MapControllers();  
  4.                 endpoints.MapBlazorHub();  
  5.                 endpoints.MapFallbackToPage("/_Host");  
  6.             });  
Now run again and check for /api/CustomerMasters/ to see the Json data from our database.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
Now we will bind all this WEB API Json result in component.
 

Working with Client Project

 
First, we need to add the Razor Component page
 

Add Razor Component

 
To add the Razor Component page right click the Pages folder from the Client project. Click on Add >> New Item >> Select Razor Component >> Enter your component name,Here we have given the name as Customerentry.razor
 
Note all the component file need to have the extentions as .razor.
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API 
 
In Razor Component Page we have 3 parts of code as first is the Import part where we import all the references and models for using in the component, HTML design and data bind part and finally we have the function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.
 

Import part

 
First, we import all the needed support files and references in our Razor View page. Here we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.
  1. @page "/customerentry"  
  2. @using BlazorCrudA1.Data  
  3. @using System.Net.Http  
  4. @inject HttpClient Http   
  5. @using Microsoft.Extensions.Logging  

Register HTTPClient for Server side Blazor

 
In order to use the HTTPClient in Blazor Server side we need to add the below code in Startup.cs ConfigureServices method.
  1. services.AddResponseCompression(opts =>  
  2.           {  
  3.               opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(  
  4.                   new[] { "application/octet-stream" });  
  5.           });  
  6.   
  7.           // Server Side Blazor doesn't register HttpClient by default  
  8.           if (!services.Any(x => x.ServiceType == typeof(HttpClient)))  
  9.           {  
  10.               // Setup HttpClient for server side in a client side compatible fashion  
  11.               services.AddScoped<HttpClient>(s =>  
  12.               {  
  13.                   // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.        
  14.                   var uriHelper = s.GetRequiredService<NavigationManager>();  
  15.                   return new HttpClient  
  16.                   {  
  17.                       BaseAddress = new Uri(uriHelper.BaseUri)  
  18.                   };  
  19.               });  
  20.           }  

HTML design and data Bind part

 
Next, we design our Customer Master details page to display the Customer details from the database and created a form to Insert and update the Customer details we also have Delete button to delete the Custoemr records from the database.
 
For binding in Blazor we use the @bind="@custObj.CustCd" and to call the method using @onclick="@AddNewCustomer"
  1. <h1> ASP.NET Core BLAZOR CRUD demo for Customers</h1>  
  2. <hr />  
  3. <table width="100%" style="background:#05163D;color:honeydew">  
  4.     <tr>  
  5.         <td width="20"> </td>  
  6.         <td>  
  7.             <h2> Add New Customer Details</h2>  
  8.         </td>  
  9.         <td> </td>  
  10.         <td align="right">  
  11.             <button class="btn btn-info" @onclick="@AddNewCustomer">Add New Customer</button>  
  12.         </td>  
  13.         <td width="10"> </td>  
  14.     </tr>  
  15.     <tr>  
  16.         <td colspan="2"></td>  
  17.     </tr>  
  18. </table>  
  19. <hr />  
  20. @if (showAddrow == true)  
  21. {  
  22.     <form>  
  23.         <table class="form-group">  
  24.             <tr>  
  25.                 <td>  
  26.                     <label for="Name" class="control-label">Customer Code</label>  
  27.                 </td>  
  28.                 <td>  
  29.                     <input type="text" class="form-control" @bind="@custObj.CustCd" />  
  30.                 </td>  
  31.                 <td width="20"> </td>  
  32.                 <td>  
  33.                     <label for="Name" class="control-label">Customer Name</label>  
  34.                 </td>  
  35.                 <td>  
  36.                     <input type="text" class="form-control" @bind="@custObj.CustName" />  
  37.                 </td>  
  38.             </tr>  
  39.             <tr>  
  40.                 <td>  
  41.                     <label for="Email" class="control-label">Email</label>  
  42.                 </td>  
  43.                 <td>  
  44.                     <input type="text" class="form-control" @bind="@custObj.Email" />  
  45.                 </td>  
  46.                 <td width="20"> </td>  
  47.                 <td>  
  48.                     <label for="Name" class="control-label">Phone</label>  
  49.                 </td>  
  50.                 <td>  
  51.                     <input type="text" class="form-control" @bind="@custObj.PhoneNo" />  
  52.                 </td>  
  53.             </tr>  
  54.             <tr>  
  55.                 <td>  
  56.                     <label for="Name" class="control-label">Insert By</label>  
  57.                 </td>  
  58.                 <td>  
  59.                     <input type="text" class="form-control" @bind="@custObj.InsertBy" />  
  60.                 </td>  
  61.                 <td width="20"> </td>  
  62.                 <td>  
  63.                 </td>  
  64.                 <td>  
  65.                     <button type="submit" class="btn btn-success" @onclick="@AddCustomer" style="width:220px;">Save</button>  
  66.                 </td>  
  67.             </tr>  
  68.         </table>  
  69.     </form>  
  70. }  
  71. <table width="100%" style="background:#0A2464;color:honeydew">  
  72.     <tr>  
  73.         <td width="20"> </td>  
  74.         <td>  
  75.             <h2>Customer List</h2>  
  76.         </td>  
  77.   
  78.     </tr>  
  79.     <tr>  
  80.         <td colspan="2"></td>  
  81.     </tr>  
  82. </table>   
  83.   
  84. @if (custs == null)  
  85. {  
  86.     <p><em>Loading...</em></p>  
  87. }  
  88. else  
  89. {  
  90.     <table class="table">  
  91.         <thead>  
  92.             <tr>  
  93.                 <th>Customer Code</th>  
  94.                 <th>Customerr Name</th>  
  95.                 <th>Email</th>  
  96.                 <th>Phone</th>  
  97.                 <th>Inserted By</th>  
  98.             </tr>  
  99.         </thead>  
  100.         <tbody>  
  101.             @foreach (var cust in custs)  
  102.             {  
  103.                 <tr>  
  104.                     <td>@cust.CustCd</td>  
  105.                     <td>@cust.CustName</td>  
  106.                     <td>@cust.Email</td>  
  107.                     <td>@cust.PhoneNo</td>  
  108.                     <td>@cust.InsertBy</td>  
  109.                     <td><button class="btn btn-primary" @onclick="@(async () => await EditCustomer(cust.CustCd))" style="width:110px;">Edit</button></td>  
  110.   
  111.                     <td><button class="btn btn-danger" @onclick="@(async () => await DeleteCustomer(cust.CustCd))">Delete</button></td>  
  112.                 </tr>  
  113.   
  114.             }  
  115.         </tbody>  
  116.     </table>  
  117. }  

Function Part

 
Function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.In this Function we create a separate function for Add, Edit and Delete the student details and call the Web API Get,Post,Put and Delete method to perform the CRUD operations and in HTML we call all the functions and bind the results.
  1. @code {  
  2.     private CustomerMaster[] custs;  
  3.     CustomerMaster custObj = new CustomerMaster();  
  4.     string ids = "0";  
  5.     bool showAddrow = false;  
  6.   
  7.     bool loadFailed;  
  8.   
  9.     protected override async Task OnInitializedAsync()  
  10.     {  
  11.         ids = "0";  
  12.         custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");  
  13.     }  
  14.     void AddNewCustomer()  
  15.     {  
  16.         ids = "0";  
  17.         showAddrow = true;  
  18.         custObj = new CustomerMaster();  
  19.     }  
  20.     // Add New Customer Details Method  
  21.     protected async Task AddCustomer()  
  22.     {  
  23.         if (ids == "0")  
  24.   
  25.         {  
  26.             await Http.SendJsonAsync(HttpMethod.Post, "/api/CustomerMasters/", custObj);  
  27.             custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");  
  28.         }  
  29.         else  
  30.         {  
  31.             await Http.SendJsonAsync(HttpMethod.Put, "/api/CustomerMasters/" + custObj.CustCd, custObj);  
  32.             custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");  
  33.         }  
  34.   
  35.         showAddrow = false;  
  36.     }  
  37.     // Edit Method  
  38.     protected async Task EditCustomer(string CustomerID)  
  39.     {  
  40.         showAddrow = true;  
  41.   
  42.         ids = "1";  
  43.         //try  
  44.         //{  
  45.         loadFailed = false;  
  46.         ids = CustomerID.ToString();  
  47.         custObj = await Http.GetJsonAsync<CustomerMaster>("/api/CustomerMasters/" + CustomerID);  
  48.   
  49.         string s = custObj.CustCd;  
  50.   
  51.         showAddrow = true;  
  52.   
  53.         //    }  
  54.         //catch (Exception ex)  
  55.         //{  
  56.         //    loadFailed = true;  
  57.         //    Logger.LogWarning(ex, "Failed to load product {ProductId}", CustomerID);  
  58.         //}  
  59.     }  
  60.     // Delte Method  
  61.     protected async Task DeleteCustomer(string CustomerID)  
  62.     {  
  63.         showAddrow = false;  
  64.   
  65.         ids = CustomerID.ToString();  
  66.         await Http.DeleteAsync("/api/CustomerMasters/" + CustomerID);  
  67.   
  68.         custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");  
  69.     }  
  70. }  

Navigation Menu

 
Now we need to add this newly added CustomerEntry Razor component to our left Navigation. For adding this Open the Shared Folder and open the NavMenu.cshtml page and add the menu.
  1. <li class="nav-item px-3">  
  2.             <NavLink class="nav-link" href="CustomerEntry">  
  3.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Customer Master  
  4.             </NavLink>  
  5.         </li>  
Build and Run the application,
 
All You Need To Know On Blazor App And Create ASP.NET Core Blazor CRUD App Using VS 2019, .NET Core 3, Web API
 

Conclusion

 
Note that when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Here we have created a table in SQL server and used with Web API you can also do this with Services and also Code First approach, Hope you all like this article. In the next article, we will see more examples to work with Blazor. It's really very cool to work with Blazor.