受欢迎的博客标签

ASP.NET Core Blazor Server(2)-Shopping Cart using EF and Web API

Published

 

Introduction

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

In this article, let’s see how to create our own ASP.NET Core Blazor Shopping Cart using Entity Framework, and Web API. Kindly read my previous articles which explain in depth about getting started with ASP.NET Core Blazor.

This article will explain:

  1. Creating a sample database with ItemDetails and ShoppingDetails table in SQL Server to display in our web application.
  2. Creating ASP.NET Core Blazor Application.
  3. Creating EF, DBContext Class, and Model Class in Blazor Shared project.
  4. Creating WEB API in Blazor Server project.
  5. Creating Razor page for displaying Item details to add items to cart.
  6. Filtering Items by Item Name. From Item textbox, keyup event displays the items by search name.
  7. Selecting and adding items to the shopping cart.
  8. Saving the selected shopping item in the database.
  9. Displaying My Shopping Order Item details.
  10. Deleting the Ordered Items.

In this shopping cart demo application, we have 3 parts.

  1. Display all items and filter items in HTML Table using ASP.NET Core Blazor from Web API.
  2. Add Items to the shopping cart and Save the shopped items to the database.
  3. Show the user Shopping Order Items in the home page. 

Display All Items and Filter Items

First, we display all item details in the shopping page using ASP.NET Core Blazor. All the item details will be loaded from Web API results and bound in Razor page. The user can also filter the items by "Item Name". When users enter any character in the "Item Name" Filter textbox, the related item details will be loaded dynamically from the database to the shopping page. 

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

Add Items to shopping cart

When the user clicks on "Image name", we display the item details at the top, to add the selected item to shopping cart. The user can add or reduce the item quantity from the selected shopping cart. The user can save the selected shopping item to the database. Here we will not focus on the user login part and we have fixed one user as “Shanu” by default.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

Shopping Order Items

In the home page, we display the user shopped order details with Item Image, Item Name, shopping description, shopped quantity, shopped amount and with delete order options.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

Prerequisites

Make sure you have installed all the prerequisites in your computer. If not, then download and install all, one by one. Note that since Blazor is the new framework, we must have installed the preview of Visual Studio 2017 (15.7) or above.

Code part

Step 1 - Create a database and a table

We will be using our SQL Server database for our WEB API and EF. First, we will create a database named ShoppingDB and a table as ItemDetails and ShoppingDetails. 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. -- =============================================    
  2. -- Author : Shanu    
  3. -- Create date : 2017-02-03  
  4. -- Description : To Create Database,Table and Sample Insert Query    
  5. -- Latest    
  6. -- Modifier : Shanu    
  7. -- Modify date : 2017-02-03    
  8. -- =============================================   
  9. --Script to create DB,Table and sample Insert data   
  10. USE MASTER   
  11. GO   
  12. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
  13. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'ShoppingDB' )   
  14. DROP DATABASE ShoppingDB   
  15. GO   
  16.    
  17. CREATE DATABASE ShoppingDB   
  18. GO   
  19.    
  20. USE ShoppingDB   
  21. GO   
  22.    
  23. -- 1) //////////// ItemDetails table   
  24. -- Create Table ItemDetails,This table will be used to store the details like Item Information     
  25.    
  26. CREATE TABLE ItemDetails   
  27. (   
  28.    Item_ID int identity(1,1),   
  29.    Item_Name VARCHAR(100) NOT NULL,   
  30.    Item_Price int NOT NULL,   
  31.    Image_Name VARCHAR(100) NOT NULL,   
  32.    Description VARCHAR(100) NOT NULL,   
  33.    AddedBy VARCHAR(100) NOT NULL,   
  34. CONSTRAINT [PK_ItemDetails] PRIMARY KEY CLUSTERED    
  35. (    
  36.    [Item_ID] ASC    
  37. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  38. ON [PRIMARY]    
  39.    
  40. GO   
  41.     
  42. -- Insert the sample records to the ItemDetails Table   
  43. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Access Point',950,'Images/AccessPoint.png','Access Point for Wifi use','Shanu')   
  44. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('CD',350,'Images/CD.png','Compact Disk','Afraz')   
  45. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Desktop Computer',1400,'Images/DesktopComputer.png','Desktop Computer','Shanu')   
  46. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('DVD',1390,'Images/DVD.png','Digital Versatile Disc','Raj')   
  47. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('DVD Player',450,'Images/DVDPlayer.png','DVD Player','Afraz')   
  48. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Floppy',1250,'Images/Floppy.png','Floppy','Mak')   
  49. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('HDD',950,'Images/HDD.png','Hard Disk','Albert')   
  50. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('MobilePhone',1150,'Images/MobilePhone.png','Mobile Phone','Gowri')   
  51. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Mouse',399,'Images/Mouse.png','Mouse','Afraz')   
  52. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('MP3 Player ',897,'Images/MultimediaPlayer.png','Multi MediaPlayer','Shanu')   
  53. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Notebook',750,'Images/Notebook.png','Notebook','Shanu')   
  54. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Printer',675,'Images/Printer.png','Printer','Kim')   
  55. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('RAM',1950,'Images/RAM.png','Random Access Memory','Jack')   
  56. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Smart Phone',679,'Images/SmartPhone.png','Smart Phone','Lee')   
  57. Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('USB',950,'Images/USB.png','USB','Shanu')   
  58.    
  59. select * from ItemDetails  
  60.   
  61.   
  62. -- 2) //////////// ShoppingDetails table   
  63. -- Create Table ShoppingDetails,This table will be used to store the user shopped items   
  64. CREATE TABLE ShoppingDetails   
  65. (   
  66.    shopId int identity(1,1),   
  67.    Item_ID int ,   
  68.    UserName VARCHAR(100) NOT NULL,   
  69.    Qty int NOT NULL,   
  70.    TotalAmount int,   
  71.    Description VARCHAR(200) NOT NULL,   
  72.    shoppingDate DateTime,   
  73. CONSTRAINT [PK_ShoppingDetails] PRIMARY KEY CLUSTERED    
  74. (    
  75.    [shopId] ASC    
  76. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  77. ON [PRIMARY]    
  78.   
  79. select * from ShoppingDetails  

Step 2 - Create ASP.NET Core Blazor Application

After installing all the prerequisites listed above and ASP.NET Core Blazor Language Services, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017 on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular Web Application. Enter your project name and click OK.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

Select Blazor (ASP.NET Core hosted) and click ok.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

After creating ASP.NET Core Blazor Application, wait for few seconds. You will see the below structure in solution explorer.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

What is new in ASP.NET Core Blazor solution?

When we will create our new ASP.NET Core Blazor application we can see as there will be 3 projects that will be automatically created in the Solution Explorer.

Client Project

The first project created is the Client project and it will be as our Solutionname.Client and here we can see our Solutionname as “BlazorASPCORE”. As the project named is a client and this project will be mainly focused for all the client-side view, here we will be adding all our page views to be displayed on the client side in the browser.

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

We can see a few of sample pages have been already added here and we can also see a shared folder like our MVC application where we will be having the Sharedfolder and Layout page for the Master page. Here in Blazor, we have the MainLayout which will work like the Master page and NavMenu for the left side menu display.

Server Project

As the name indicates, this project will be used as a Server project. This project is mainly used to create all our Controllers and WEB API Controllers to perform all business logic and perform CRUD operations using WEB-APIs. In our demo application, we will be adding a Web API in this Server project and all the WEB API in our Client application. This Server project will be  getting/setting the data from the Database, and from our Client project we bind or send the result to this server to perform the CRUD operation in the database.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Shared Project

As the name is indicating, this project works like a shared project. This project works as a Model for our Server project and for the Client project. The Model declared in this Shared project will be used in both the Server and in the Client project. We will also install all the packages needed for our project here, for example, to use the Entity Framework we have to install all the packages in this Shared project.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

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 them and start with our own page.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Now, let’s see how to add a new page to make the online Shopping website.

Using Entity Framework

To use the Entity Framework in our Blazor application we need to install the below packages.

Install the Packages

Go to Tools and then select -> NuGet Package Manager -> Package Manager Console.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

You can see the Console at the bottom of the VS 2017 IDE and in the right side of the combo box on the console select the Default project as your shared project” Select Shared”

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

  • You can see the PM> and copy and paste the below line to install the Database Provider package. This package is used to set the database provider as SQL Server.

Install-Package Microsoft.EntityFrameworkCore.SqlServer

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

We can see as the package is installed in our Shared folder

Install the Entity Framework

  • You can see the PM> and copy and paste the below line to install the EF package.

    Install-Package Microsoft.EntityFrameworkCore.Tools

    make Shopping Cart using ASP.NET Core Blazor using EF and Web API

    To Create DB Context and set the DB Connection string
  • You can see the PM> and copy and paste the below line to set the Connection string and create DB Context. This is an important part as we give our SQL Server name, Database Name and SQL server UID and SQL Server Password to connect to our database to display our Shopping Cart details. We also give our both SQL Table name “ItemDetails, ShoppingDetails” to create the Model class in our Shared project.
     
    1. Scaffold-DbContext "Server= YourServerName;  
    2. Database=ShoppingDB;  
    3. userid=SQLID;  
    4. password=SQLPWD;  
    5. Trusted_Connection=True;  
    6. MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables ItemDetails ,ShoppingDetails  

Press enter create connection string, Model Class and Database Context.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

We can see the ItemDetails and ShoppingDetails Model class and ShoppingDBContext class have been created in our Shared project. We will be using this Model and DBContext in our Server project to create our Web API. 

Creating Web API for Getting Item details

To create our WEB API Controller, right-click trollers folder. Click Add New Controller.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Here, we will be using Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Select our Model and DatabaseContext from the Shared project.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Select our ItemDetails Model from the Shared Project.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Select the Data Context Class as our ShoppingDBContext from the Shared project. Our Controller name will be automatically added, and if you need to you can change it and click the ADD.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

We will be using only the Get method from our Web API.

Like this we also create a Web API for our ShoppingDetails.

In ShoppingDetails Web API controller get method we will be using the LINQ join query to select both Item and Shopping Details to be bound in home page to display the Item Details along with the shopping details to the users.

 
  1. [HttpGet]  
  2.       public IEnumerable<myShopping> GetShoppingDetails()  
  3.       {  
  4.           var results = (from items in _context.ItemDetails  
  5.                          join shop in _context.ShoppingDetails  
  6.                               on items.ItemId equals shop.ItemId  
  7.                          select new myShopping  
  8.                          {  
  9.   
  10.                              ShopId = shop.ShopId,  
  11.                              ItemName = items.ItemName,  
  12.                              ImageName = items.ImageName,  
  13.                              UserName = shop.UserName,  
  14.                              Qty = shop.Qty,  
  15.                              TotalAmount = shop.TotalAmount,  
  16.                              Description = shop.Description,  
  17.                              ShoppingDate = shop.ShoppingDate  
  18.                     }).ToList();  
  19.   
  20.   
  21.           return results;  
  22.       }  

To test the Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get api/ItemDetails /

Run the program and paste API path to test our output.

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

For ShoppingDetails, we can get both the Itemdetails and ShoppingDetails table result. Here, we can see the result from Web API path /api/ ShoppingDetails

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Now we will bind all these WEB API JSON results in our Razor View page from our Client project for displaying the Shopping List.

Working with Client Project

Note
In this article, we will create 2 Razor pages. In one Razor page, we will display the Item Details and users can do shopping by adding selected items to cart and save the shopping details to the database. In Homepage, we bind the shopping details of users with both Item and Shopping details.

Creating Shopping Page

Add Razor View

To add the Razor view page, right click the Pages folder from the Client project. Click on Add >> New Item

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Select Razor View >> Enter your page name, here we have given the name as Shopping.chtml

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

In the Razor view page we have 3 parts of code,  as  the first is the import part where we import all the references and models for using in the view, HTML design, and data binding part; and finally, we have the function part to call all the web APIs to bind in our HTML page and also to perform client-side business logic to be displayed in View 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 bind the resultant JSON in our Razor page.

 
  1. @page "/Shopping"  
  2. @using BlazorShoppingCarts.Shared  
  3. @using BlazorShoppingCarts.Shared.Models  
  4. @using Microsoft.AspNetCore.Blazor.Browser.Interop  
  5. @using System.Collections.Generic  
  6. @using Microsoft.AspNetCore.Blazor   
  7. @inject HttpClient Http  

Display All Items and Filter Items

Firstly we bind the Item details with Filter options and the user can add items for shopping by clicking on the Image.

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

Here, we bind all the Item Details.

HTML Part to Bind Item Details with Filter code

In the Init method, we get the ItemDetails from Web API and bind the result in an HTML table using a Foreach loop. We add the options as filter items from the Grid. For this we have added a new row in our table and added a textbox for filtering items for the ItemName. In the Filtering textbox onChange event, we pass the pressed key value to filter the Items. In Item List, we also bind the items with Image and in Image click, we add the selected item to Shopping Cart for shopping.

 
  1. @if (itmDetail == null)  
  2.                           {  
  3.                               <p><em>Loading...</em></p>  
  4.                           }  
  5.                           else  
  6.                           {  
  7.                               <table style="background-color:#FFFFFF; border: solid 2px #6D7B8D; padding: 5px;width: 100%;table-layout:fixed;" cellpadding="2" cellspacing="2">  
  8.   
  9.   
  10.                                   <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  11.                                       <td width="40" align="center">  
  12.                                           <b>Image</b>  
  13.                                       </td>  
  14.   
  15.                                       <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">  
  16.                                           <b>Item Code</b>  
  17.                                       </td>  
  18.   
  19.                                       <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">  
  20.                                           <b>Item Name</b>  
  21.                                       </td>  
  22.   
  23.                                       <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">  
  24.                                           <b>Decription</b>  
  25.                                       </td>  
  26.   
  27.                                       <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">  
  28.                                           <b>Price</b>  
  29.                                       </td>  
  30.   
  31.                                       <td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">  
  32.                                           <b>User Name</b>  
  33.                                       </td>  
  34.                                   </tr>  
  35.                                   <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  36.                                       <td width="40" align="center">  
  37.                                           Filter By ->  
  38.                                       </td>  
  39.   
  40.                                       <td style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  41.   
  42.                                           Item Name :  
  43.                                       </td>  
  44.                                       <td width="200" colspan="4" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  45.                                           <input width="70" onchange=@OnItemNameChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />  
  46.                                       </td>  
  47.   
  48.                                   </tr>  
  49.                                   <tbody>  
  50.                                       @foreach (var itmDtl in itmDetail)  
  51.                                       {  
  52.                                           <tr>  
  53.                                               <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  54.                                                   <span style="color:#9F000F">  
  55.                                                       <img src="@itmDtl.ImageName" style="height:56px;width:56px" onclick="@(async () => await AddItemtoShoppingCart(@itmDtl))" />  
  56.                                                   </span>  
  57.   
  58.                                               </td>  
  59.                                               <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  60.                                                   <span style="color:#9F000F">  
  61.                                                       @itmDtl.ItemId  
  62.                                                   </span>  
  63.                                               </td>  
  64.   
  65.                                               <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  66.                                                   <span style="color:#9F000F">  
  67.                                                       @itmDtl.ItemName  
  68.                                                   </span>  
  69.                                               </td>  
  70.   
  71.                                               <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  72.                                                   <span style="color:#9F000F">  
  73.                                                       @itmDtl.Description  
  74.                                                   </span>  
  75.                                               </td>  
  76.   
  77.                                               <td align="right" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  78.                                                   <span style="color:#9F000F">  
  79.                                                       @itmDtl.ItemPrice  
  80.                                                   </span>  
  81.                                               </td>  
  82.   
  83.   
  84.                                               <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  85.                                                   <span style="color:#9F000F">  
  86.                                                       @itmDtl.AddedBy  
  87.                                                   </span>  
  88.                                               </td>  
  89.                                           </tr>  
  90.                                       }  
  91.                                   </tbody>  
  92.                               </table>  
  93.                           }  

Blazor Function part to bind the Item Details to HTML Grid with Filter functions

Function Part

Function part calls the web API to bind in our HTML page and also performs client-side business logic to be displayed in View page. In the function part, we first declare all the objects needed for our page.

 
  1. @functions {  
  2.                    string UserName = "Shanu";  
  3.                    string selectItemImage = "";  
  4.                    string selectedItemName = "";  
  5.                    int initialPrice = 0;  
  6.                    string Messages = "";  
  7.   
  8.                    ShoppingDetails[] shoppingDetails;  
  9.                    ItemDetails[] itmDetail;  
  10.   
  11.                    ShoppingDetails SD = new ShoppingDetails();  
  12.                    ItemDetails ID = new ItemDetails();  
  13.   
  14.                    Boolean showAddtoCart = false;  

Init Method

In the Init method, we get the result of Web API for ItemDetails and store it in the itmDetail object. We are using this object to be bound in our HTML table using the foreach statement.

In the Item Name column heading part, we have added a new row for performing the Filtering of the HTML grid. In the ItemName Column filter Textbox Change event, we pass the Textbox value. We call a common filtering method, FilteringList, and in this method, we pass the filtering column Textbox value and column Name to filter the ItemDetails and bind the result to HTML grid.

 
  1. protected override async Task OnInitAsync()  
  2.                   {  
  3.                       itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");  
  4.                   }  
  5.   
  6.                   // For Filtering by Item Name  
  7.                   void OnItemNameChanged(UIChangeEventArgs args)  
  8.                   {  
  9.                       string values = args.Value.ToString();  
  10.                       FilteringList(values);  
  11.                   }  
  12.   
  13.                   //Filtering  
  14.                   protected async Task FilteringList(String Value)  
  15.                   {  
  16.                       itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");  
  17.   
  18.                       if (Value.Trim().Length > 0)  
  19.                       {  
  20.                           itmDetail = itmDetail.Where(x => x.ItemName.Contains(Value)).ToArray();  
  21.                       }  
  22.                       else  
  23.                       {  
  24.                           itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");  
  25.                       }  
  26.                   }  

Add Items to shopping cart

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

Users can add items to Shopping Cart by clicking on the Item Image from List. In the item image click we call the functions to bind the result to shopping cart for shopping. By default, we hide the shopping part from users and we set the showAddtoCart as false in page load and when the user clicks on the Item Image we set the showAddtoCart to true to display the Shopping details. Here is the HTML part to design the shopping part.

 
  1. @if (showAddtoCart == true)  
  2.             {  
  3.                 <table style="background-color:#FFFFFF; border: dashed 3px #d55500; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2"  
  4.                        cellspacing="6">  
  5.                     <tr style="height: 30px;  color:#336699 ;border: solid 1px #659EC7;">  
  6.                         <td width="40px"> <img src="Images/shopping_cart64.png" height="38" width="38" /></td>  
  7.                         <td>  
  8.                              
  9.                             <h2> <strong>Add Items to Cart</strong></h2>  
  10.                         </td>  
  11.   
  12.                     </tr>  
  13.                     <tr>  
  14.                         <td width="10px"> </td>  
  15.                         <td>  
  16.                             <table >   
  17.                                     <tr >   
  18.                                         <td style="width:250px;-moz-box-shadow: inset 0 0 5px #888;  
  19.     -webkit-box-shadow: inset 0 0 5px #888;  
  20.     box-shadow: inset 1px 1px 5px #888;  
  21.     display: block;">  
  22.   
  23.                                             <img src="@selectItemImage" style="height:250px;width:250px" />  
  24.   
  25.                                         </td>  
  26.                                        <td width="10"></td>  
  27.                                         <td align="left" width="500px" valign="top">  
  28.                                             <table style="width:500px;color:#9F000F;font-size:large;width:98%;" cellpadding="4" cellspacing="6">  
  29.                                                 <tr style="height: 30px;  color:#416048 ;border-bottom: solid 1px #659EC7;">  
  30.                                                     <td>  
  31.                                                         <h2>  
  32.                                                             @selectedItemName  
  33.                                                         </h2>  
  34.                                                     </td>  
  35.                                                 </tr>  
  36.                                                 <tr style="height: 30px;  color:#e13a19 ;border-bottom: solid 1px #659EC7;">  
  37.                                                     <td>  
  38.                                                         <h3>  
  39.                                                             Price : @initialPrice  
  40.                                                         </h3>  
  41.   
  42.                                                     </td>  
  43.                                                 </tr>  
  44.   
  45.                                                 <tr style="height: 30px;  color:#3a729a ;border-bottom: solid 1px #659EC7;">  
  46.                                                     <td>  
  47.                                                         <table>  
  48.                                                             <tr>  
  49.                                                                 <td>  
  50.                                                                     <h3>  
  51.                                                                         Qty : @SD.Qty  
  52.                                                                     </h3>  
  53.                                                                 </td>  
  54.                                                                 <td>  
  55.                                                                     <table>  
  56.                                                                         <tr>  
  57.                                                                             <td>  
  58.                                                                                 <img src="Images/UP.png" height="20" width="20" onclick="@IncreaseQty" />  
  59.                                                                             </td>  
  60.   
  61.                                                                         </tr>  
  62.                                                                         <tr>  
  63.                                                                             <td>  
  64.                                                                                 <img src="Images/Down.png" height="20" width="20" onclick="@DecreaseQty" />  
  65.                                                                             </td>  
  66.   
  67.                                                                         </tr>  
  68.                                                                     </table>  
  69.                                                                 </td>  
  70.                                                                 <td  style="color:#e13a19 ;">  
  71.                                                                     <h4>  
  72.                                                                         Total Amount : @SD.TotalAmount  
  73.                                                                     </h4>  
  74.                                                                 </td>  
  75.                                                             </tr>  
  76.                                                               
  77.   
  78.                                                         </table>  
  79.   
  80.   
  81.                                                     </td>  
  82.                                                 </tr>  
  83.   
  84.                                                 <tr style="height: 30px;  color:#e13a19 ;">  
  85.                                                     <td>  
  86.                                                         <h3>  
  87.                                                             Notes :  <input type="text" class="form-control" bind="@SD.Description" />  
  88.                                                         </h3>  
  89.   
  90.                                                     </td>  
  91.                                                 </tr>  
  92.                                                 <tr >  
  93.                                                     <td>  
  94.                                                         <h3>  
  95.                                                             <button type="submit" class="btn btn-success" onclick="@(async () => await SaveShoppingetails())" style="width:220px;">  
  96.                                                                 <img src="Images/shopping_cart64.png" height="32" width="32" /> BUY NOW</button>  
  97.                                                         </h3>  
  98.   
  99.                                                     </td>  
  100.                                                 </tr>  
  101.   
  102.                                             </table>  
  103.                                         </td>  
  104.                                     </tr>  
  105.                                 </table>  
  106.                             </td>  
  107.                         </tr>  
  108.                     </table>  
  109.                                 }  

Item Image click event

When the user clicks on the Item Image from the list we call the AddItemtoShoppingCart and pass the selected ItemDetails to the function. In this function firstly, we set the showAddtoCart as true to show the Shopping list. We also bind the selected Item details to shoping list to add in Cart.

 
  1. protected async Task AddItemtoShoppingCart(ItemDetails itemAdd)  
  2.                   {  
  3.                       showAddtoCart = true;  
  4.                       initialPrice = 0;  
  5.   
  6.                       SD.ItemId = itemAdd.ItemId;  
  7.                       selectedItemName = itemAdd.ItemName;  
  8.                       SD.Qty = 1;  
  9.                       initialPrice = itemAdd.ItemPrice;  
  10.                       SD.TotalAmount = itemAdd.ItemPrice;  
  11.   
  12.                       SD.UserName = UserName;  
  13.                       selectItemImage = itemAdd.ImageName;  
  14.                       SD.ShoppingDate = DateTime.Now;  
  15.                       SD.Description = "";  
  16.                   }  

Shopping Cart Quantity Add and Reduce

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

In Shopping Cart user can increase /decrease the shopping Quantity and when user clicks on the up Image near Qty then we call the IncreaseQty method and in this method, we increment the Quantity and also update the Total Amount. It's the same as when a user clicks on the down icon. We call DecreaseQty method to do it in reverse order to decrement the quantity along with updating the Total Amount.

 
  1. void IncreaseQty()  
  2.                   {  
  3.                       if (SD.Qty > 0)  
  4.                       {  
  5.                           SD.Qty = SD.Qty + 1;  
  6.   
  7.                           SD.TotalAmount = initialPrice * SD.Qty;  
  8.   
  9.                       }  
  10.   
  11.                   }  
  12.   
  13.   
  14.                   void DecreaseQty()  
  15.                   {  
  16.                       if (SD.Qty > 1)  
  17.                       {  
  18.   
  19.                           SD.Qty = SD.Qty - 1;  
  20.                           SD.TotalAmount = initialPrice * SD.Qty;  
  21.                       }  
  22.                   }  

Save the Shopping List

Finally, when user clicks on the Buy Now button we pass the shopping details to save the result in our ShoppingDetails table in our database.

 
  1. //Save Shopping Details  
  2.    protected async Task SaveShoppingetails()  
  3.                   {  
  4.                       await Http.SendJsonAsync(HttpMethod.Post, "/api/ShoppingDetails/", SD);  
  5.                       Messages = "Your Shopping is completed! Enjoy more shopping from my Site :)";  
  6.                       SD = null;  
  7.                       showAddtoCart = false;  
  8.                   }  

Shopping Order Items

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

In the home page we bind the user's shopping details with Item Name, Image, Order Date, Ordered Quantity and total amount. Users can also cancel the Order from the home page. When a user clicks on the Cancel Order we delete the shopping order details from the table.

 
  1. @if (myShopList == null)  
  2.                 {  
  3.                     <p><em>Loading...</em></p>  
  4.                 }  
  5.                 else  
  6.                 {  
  7.   
  8.                     @foreach (var myShoppings in myShopList)  
  9.                     {  
  10.                         <table>  
  11.                             <tr>  
  12.                                 <td>  
  13.   
  14.   
  15.                                     <table class="divContainer">  
  16.                                         <tr>  
  17.                                             <td align="left" width="112px">  
  18.                                                 <span style="color:#9F000F">  
  19.                                                     <img src="@myShoppings.ImageName" style="height:110px;width:110px" />  
  20.                                                 </span>  
  21.                                             </td>  
  22.                                             <td align="left" valign="top">  
  23.                                                 <table>  
  24.                                                     <tr>  
  25.                                                         <td valign="top">  
  26.                                                             <h2 style="color:#244f2b">@myShoppings.ItemName </h2>  
  27.                                                         </td>  
  28.                                                     </tr>  
  29.                                                     <tr>  
  30.                                                         <td>  
  31.                                                             Order Date : @myShoppings.ShoppingDate.Value.ToString("yyyy-MM-dd HH:mm")  
  32.                                                         </td>  
  33.                                                     </tr>  
  34.                                                     <tr>  
  35.                                                         <td>  
  36.                                                             @myShoppings.Description  
  37.                                                         </td>  
  38.                                                     </tr>  
  39.                                                     <tr>  
  40.                                                         <td>  
  41.                                                             <h3 style="color:#ff0000">  @myShoppings.TotalAmount (INR) /  @myShoppings.Qty (QTY)</h3>  
  42.                                                         </td>  
  43.                                                     </tr>  
  44.                                                 </table>  
  45.                                             </td>  
  46.                                             <td>  
  47.                                                 <h3>  
  48.                                                     <button type="submit" class="btn btn-danger" onclick="@(async () => await deleteConfirm(@myShoppings))" style="width:220px;">  
  49.                                                         <img src="Images/delete.png"  /> Cancel Order  
  50.                                                     </button>  
  51.                                                 </h3>  
  52.                                             </td>  
  53.                                         </tr>  
  54.   
  55.                                     </table>  
  56.                                 </td>  
  57.                             </tr>  
  58.                             <tr>  
  59.                                 <td style="height:10px;">  
  60.                                        
  61.                                 </td>  
  62.                             </tr>  
  63.                         </table>  
  64.                     }  
  65.                 }  

In the function part, first we declare all the object needed for this page and in Init method we load all the ShoppingDetails and bind the result in HTML grid.

 
  1. @functions {  
  2.         string UserName = "Shanu";  
  3.         ShoppingDetails SD = new ShoppingDetails();  
  4.         string Messages = "";  
  5.         myShopping[] myShopList;  
  6.         int shopID = 0;    
  7. protected override async Task OnInitAsync()  
  8.         {  
  9.             shopID = 0;  
  10.             myShopList = await Http.GetJsonAsync<myShopping[]>("/api/ShoppingDetails/");  
  11.         }  

Cancel Order

 

make Shopping Cart using ASP.NET Core Blazor using EF and Web API

 

When users click on the Cancel Order button we call the deleteConfirm method and pass the selected ShoppingDetails ID for deletion. Before deletion we get the conformation message as “Are you Sure to Cancel your Item order “ .

 
  1. @if (Messages != "")  
  2. {  
  3. <div id="outPopUp" style="position: absolute;  width: 552px;  height: 320px;  z-index: 15;  top: 38%;  left: 50%;  margin: -100px 0 0 -150px;  background: #fbde5a;">  
  4.     <div id="outPopUp" style="position: absolute;  width: 551px;  height: 248px;    background: #fc3a2e;">  
  5.         <img src="Images/C1.png" onclick="@closeMessage" />  
  6.         <span style="color:#ECF3F4;font-size:xx-large;display: inline-block;    margin: 10px 10px 0 0;   padding: 5px 10px ">  
  7.             @Messages  
  8.         </span>  
  9.     </div>  
  10.     <div id="outPopUp" style="position: absolute; top:260px; width:350px;left:24%; height: 70px; ">  
  11.         <h3>  
  12.             <button type="submit" class="btn btn-success" onclick="@(async () => await deleteShopping())" style="width:150px;">  
  13.                 <img src="Images/tick.png" height="32px" width="32px"/>   Ok  
  14.             </button>  
  15.             <button type="submit" class="btn btn-danger" onclick="@closeMessage" style="width:150px;">  
  16.                 <img src="Images/delete1.png" height="32px" width="32px"/>  Cancel  
  17.             </button>  
  18.         </h3>  
  19.     </div>  
  20. </div>  
  21.     }  
  22.   
  23.    protected async Task deleteConfirm(myShopping sds)  
  24.         {  
  25.   
  26.             shopID = sds.ShopId;  
  27.             Messages = "Are you Sure to Cancel your " + sds.ItemName + " Order ?";  
  28.         }  

If user clicks on ok button we call the deleteShopping method and in this method, we delete the ShoppingDetails by the selected Shopping ID. If a user clicks on the Cancel button then we hide the Confirmation message and cancel deleting the Shopping order.

 
  1. protected async Task deleteShopping()  
  2.      {  
  3.          await Http.DeleteAsync("/api/ShoppingDetails/" + Convert.ToInt32(shopID));  
  4.          Messages = "";  
  5.          myShopList = await Http.GetJsonAsync<myShopping[]>("/api/ShoppingDetails/");  
  6.      }    
  7.   
  8.      void closeMessage()  
  9.      {  
  10.          shopID = 0;  
  11.          Messages = "";   
  12.      }  

Navigation Menu

Now we need to add this newly added Shopping Razor page 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="" Match=NavLinkMatch.All>  
  3.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  4.             </NavLink>  
  5.         </li>  
  6.         <li class="nav-item px-3">  
  7.             <NavLink class="nav-link" href="Shopping">  
  8.                 <img src="Images/shopping_cart64.png" height="32" width="32" />   Let's Shop  
  9.             </NavLink>  
  10.         </li>  

Conclusion

When creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. I hope you like this article, and in the next article we will see more examples to work with Blazor.  It's really very cool and awesome to work with Blazor.