Introduction  


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 explains in depth about getting started with ASP.NET Core Blazor.

This article will explain on:  

  1. Creating 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 Itemdetails 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 shopping cart.
  8. Save the selected shopping item to database.
  9. Displaying My Shopping Order Item details.
  10. Delete 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 shopping cart and Save the shopped items to database.
  3. Show the user Shopping Order Items in 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 binded in Razor page. 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. 

Add Items to shopping cart

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

Shopping Order Items

In 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.


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 and we must have installed 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 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.

-- =============================================  
-- Author : Shanu  
-- Create date : 2017-02-03
-- Description : To Create Database,Table and Sample Insert Query  
-- Latest  
-- Modifier : Shanu  
-- Modify date : 2017-02-03  
-- ============================================= 
--Script to create DB,Table and sample Insert data 
USE MASTER 
GO 
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB 
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ShoppingDB' ) 
DROP DATABASE ShoppingDB 
GO 
   
CREATE DATABASE ShoppingDB 
GO 
   
USE ShoppingDB 
GO 
   
-- 1) //////////// ItemDetails table 
-- Create Table ItemDetails,This table will be used to store the details like Item Information   
   
CREATE TABLE ItemDetails 
Item_ID int identity(1,1), 
Item_Name VARCHAR(100) NOT NULL, 
Item_Price int NOT NULL, 
Image_Name VARCHAR(100) NOT NULL, 
Description VARCHAR(100) NOT NULL, 
AddedBy VARCHAR(100) NOT NULL, 
CONSTRAINT [PK_ItemDetails] PRIMARY KEY CLUSTERED  
(  
[Item_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]  
   
GO 
    
-- Insert the sample records to the ItemDetails Table 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Access Point',950,'Images/AccessPoint.png','Access Point for Wifi use','Shanu') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('CD',350,'Images/CD.png','Compact Disk','Afraz') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Desktop Computer',1400,'Images/DesktopComputer.png','Desktop Computer','Shanu') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('DVD',1390,'Images/DVD.png','Digital Versatile Disc','Raj') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('DVD Player',450,'Images/DVDPlayer.png','DVD Player','Afraz') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Floppy',1250,'Images/Floppy.png','Floppy','Mak') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('HDD',950,'Images/HDD.png','Hard Disk','Albert') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('MobilePhone',1150,'Images/MobilePhone.png','Mobile Phone','Gowri') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Mouse',399,'Images/Mouse.png','Mouse','Afraz') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('MP3 Player ',897,'Images/MultimediaPlayer.png','Multi MediaPlayer','Shanu') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Notebook',750,'Images/Notebook.png','Notebook','Shanu') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Printer',675,'Images/Printer.png','Printer','Kim') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('RAM',1950,'Images/RAM.png','Random Access Memory','Jack') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('Smart Phone',679,'Images/SmartPhone.png','Smart Phone','Lee') 
Insert into ItemDetails(Item_Name,Item_Price,Image_Name,Description,AddedBy) values('USB',950,'Images/USB.png','USB','Shanu') 
   
select * from ItemDetails
  
  
-- 2) //////////// ShoppingDetails table 
-- Create Table ShoppingDetails,This table will be used to store the user shopped items 
CREATE TABLE ShoppingDetails 
shopId int identity(1,1), 
Item_ID int , 
UserName VARCHAR(100) NOT NULL, 
Qty int NOT NULL, 
TotalAmount int, 
Description VARCHAR(200) NOT NULL, 
shoppingDate DateTime, 
CONSTRAINT [PK_ShoppingDetails] PRIMARY KEY CLUSTERED  
(  
[shopId] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  
  
select * from ShoppingDetails

Step 2 - Create ASP.NET Core Blazor Application

fter 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.


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

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

What is new in ASP.NET Core Blazor solution?

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

Client Project

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


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

Server Project

As the name indicating 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 operation using WEB API’s. 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 work like get/set the data from Database and from our Client project we bind or send the result to this server to perform the CRUD operation in database.



Shared Project

As the name indicating this project work like a shred 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 also install all the packages needed for our project here, for example, to use the Entity Framework we install all the packages in this Shared project.

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.


Now let’s see how to add new page perform 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.



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

1)       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

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

Install the Entity Framework

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

Install-Package Microsoft.EntityFrameworkCore.Tools

To Create DB Context and set the DB Connection string

   3) You can see the PM> and copy and paste the below line 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 for performing the CRUD operation. We also give our SQL Table name to create the Model class in our Shared project.
Scaffold-DbContext "Server= YourServerName;Database=ShoppingDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables ItemDetails ,ShoppingDetails

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

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

Working with Web API 

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



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



Select our Model and DatabaseContext from the Shared project.


Select our ItemDetails Model from the Shared Project.


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

Same 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 bind in home page to display the Item Details along with the shopping details to the users.

[HttpGet]
        public IEnumerable<myShopping> GetShoppingDetails()
        {
            var results = (from items in _context.ItemDetails
                           join shop in _context.ShoppingDetails
                                on items.ItemId equals shop.ItemId
                           select new myShopping
                           {
  
                               ShopId = shop.ShopId,
                               ItemName = items.ItemName,
                               ImageName = items.ImageName,
                               UserName = shop.UserName,
                               Qty = shop.Qty,
                               TotalAmount = shop.TotalAmount,
                               Description = shop.Description,
                               ShoppingDate = shop.ShoppingDate
                      }).ToList();
  
  
            return results;
        }
 

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 item to cart and do save the shopped details to the database. In Home page 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


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

In Razor view 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 view, 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 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.
@page "/Shopping"
@using BlazorShoppingCarts.Shared
@using BlazorShoppingCarts.Shared.Models
@using Microsoft.AspNetCore.Blazor.Browser.Interop
@using System.Collections.Generic
@using Microsoft.AspNetCore.Blazor 
@inject HttpClient Http

Display All Items and Filter Items

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

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 HTML table using foreach loop. We add the options as filter items from grid for this we have added a new row in our table and added a textbox for filtering item 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.

@if (itmDetail == null)
                            {
                                <p><em>Loading...</em></p>
                            }
                            else
                            {
                                <table style="background-color:#FFFFFF; border: solid 2px #6D7B8D; padding: 5px;width: 100%;table-layout:fixed;" cellpadding="2" cellspacing="2">
  
  
                                    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                                        <td width="40" align="center">
                                            <b>Image</b>
                                        </td>
  
                                        <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">
                                            <b>Item Code</b>
                                        </td>
  
                                        <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">
                                            <b>Item Name</b>
                                        </td>
  
                                        <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">
                                            <b>Decription</b>
                                        </td>
  
                                        <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">
                                            <b>Price</b>
                                        </td>
  
                                        <td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;">
                                            <b>User Name</b>
                                        </td>
                                    </tr>
                                    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                                        <td width="40" align="center">
                                            Filter By ->
                                        </td>
  
                                        <td style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">
  
                                            Item Name :
                                        </td>
                                        <td width="200" colspan="4" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">
                                            <input width="70" onchange=@OnItemNameChanged oninput="(this.dispatchEvent(new CustomEvent('change', {bubbles: true})))" />
                                        </td>
  
                                    </tr>
                                    <tbody>
                                        @foreach (var itmDtl in itmDetail)
                                        {
                                            <tr>
                                                <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        <img src="@itmDtl.ImageName" style="height:56px;width:56px" onclick="@(async () => await AddItemtoShoppingCart(@itmDtl))" />
                                                    </span>
  
                                                </td>
                                                <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        @itmDtl.ItemId
                                                    </span>
                                                </td>
  
                                                <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        @itmDtl.ItemName
                                                    </span>
                                                </td>
  
                                                <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        @itmDtl.Description
                                                    </span>
                                                </td>
  
                                                <td align="right" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        @itmDtl.ItemPrice
                                                    </span>
                                                </td>
  
  
                                                <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                                    <span style="color:#9F000F">
                                                        @itmDtl.AddedBy
                                                    </span>
                                                </td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            }

Blazor Function part 

Function Part and Init method to bind the Item Details to HTML Grid with Filter functions

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

@functions {
                  string UserName = "Shanu";
                  string selectItemImage = "";
                  string selectedItemName = "";
                  int initialPrice = 0;
                  string Messages = "";
 
                  ShoppingDetails[] shoppingDetails;
                  ItemDetails[] itmDetail;
 
                  ShoppingDetails SD = new ShoppingDetails();
                  ItemDetails ID = new ItemDetails();
 
                  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 bind in our HTML table using the foreach statement.

In Item Name column heading part, we have added a new row for performing the Filtering of the HTML grid. In 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.

protected override async Task OnInitAsync()
                   {
                       itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");
                   }
 
                   // For Filtering by Item Name
                   void OnItemNameChanged(UIChangeEventArgs args)
                   {
                       string values = args.Value.ToString();
                       FilteringList(values);
                   }
 
                   //Filtering
                   protected async Task FilteringList(String Value)
                   {
                       itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");
 
                       if (Value.Trim().Length > 0)
                       {
                           itmDetail = itmDetail.Where(x => x.ItemName.Contains(Value)).ToArray();
                       }
                       else
                       {
                           itmDetail = await Http.GetJsonAsync<ItemDetails[]>("/api/ItemDetails/");
                       }
                   }

Add Items to shopping cart



Users can add items to Shopping Cart by clicking on the Item Image from List. In item image click we call the functions to bind the result to shopping cart for shopping. By default we hide the shopping part to 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.
@if (showAddtoCart == true)
            {
                <table style="background-color:#FFFFFF; border: dashed 3px #d55500; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2"
                       cellspacing="6">
                    <tr style="height: 30px;  color:#336699 ;border: solid 1px #659EC7;">
                        <td width="40px"> <img src="Images/shopping_cart64.png" height="38" width="38" /></td>
                        <td>
                             
                            <h2> <strong>Add Items to Cart</strong></h2>
                        </td>
  
                    </tr>
                    <tr>
                        <td width="10px"> </td>
                        <td>
                            <table
                                    <tr
                                        <td style="width:250px;-moz-box-shadow: inset 0 0 5px #888;
    -webkit-box-shadow: inset 0 0 5px #888;
    box-shadow: inset 1px 1px 5px #888;
    display: block;">
  
                                            <img src="@selectItemImage" style="height:250px;width:250px" />
  
                                        </td>
                                       <td width="10"></td>
                                        <td align="left" width="500px" valign="top">
                                            <table style="width:500px;color:#9F000F;font-size:large;width:98%;" cellpadding="4" cellspacing="6">
                                                <tr style="height: 30px;  color:#416048 ;border-bottom: solid 1px #659EC7;">
                                                    <td>
                                                        <h2>
                                                            @selectedItemName
                                                        </h2>
                                                    </td>
                                                </tr>
                                                <tr style="height: 30px;  color:#e13a19 ;border-bottom: solid 1px #659EC7;">
                                                    <td>
                                                        <h3>
                                                            Price : @initialPrice
                                                        </h3>
  
                                                    </td>
                                                </tr>
  
                                                <tr style="height: 30px;  color:#3a729a ;border-bottom: solid 1px #659EC7;">
                                                    <td>
                                                        <table>
                                                            <tr>
                                                                <td>
                                                                    <h3>
                                                                        Qty : @SD.Qty
                                                                    </h3>
                                                                </td>
                                                                <td>
                                                                    <table>
                                                                        <tr>
                                                                            <td>
                                                                                <img src="Images/UP.png" height="20" width="20" onclick="@IncreaseQty" />
                                                                            </td>
  
                                                                        </tr>
                                                                        <tr>
                                                                            <td>
                                                                                <img src="Images/Down.png" height="20" width="20" onclick="@DecreaseQty" />
                                                                            </td>
  
                                                                        </tr>
                                                                    </table>
                                                                </td>
                                                                <td  style="color:#e13a19 ;">
                                                                    <h4>
                                                                        Total Amount : @SD.TotalAmount
                                                                    </h4>
                                                                </td>
                                                            </tr>
                                                              
  
                                                        </table>
  
  
                                                    </td>
                                                </tr>
  
                                                <tr style="height: 30px;  color:#e13a19 ;">
                                                    <td>
                                                        <h3>
                                                            Notes :  <input type="text" class="form-control" bind="@SD.Description" />
                                                        </h3>
  
                                                    </td>
                                                </tr>
                                                <tr >
                                                    <td>
                                                        <h3>
                                                            <button type="submit" class="btn btn-success" onclick="@(async () => await SaveShoppingetails())" style="width:220px;">
                                                                <img src="Images/shopping_cart64.png" height="32" width="32" /> BUY NOW</button>
                                                        </h3>
  
                                                    </td>
                                                </tr>
  
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                                }

Item Image click event

When user click 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.

protected async Task AddItemtoShoppingCart(ItemDetails itemAdd)
                    {
                        showAddtoCart = true;
                        initialPrice = 0;
  
                        SD.ItemId = itemAdd.ItemId;
                        selectedItemName = itemAdd.ItemName;
                        SD.Qty = 1;
                        initialPrice = itemAdd.ItemPrice;
                        SD.TotalAmount = itemAdd.ItemPrice;
  
                        SD.UserName = UserName;
                        selectItemImage = itemAdd.ImageName;
                        SD.ShoppingDate = DateTime.Now;
                        SD.Description = "";
                    }

Shopping Cart Quantity Add and Reduce

In Shopping Cart user can increase /decrease the shopping Quantity and when user clicks on the up Image nearby Qty then we call the IncreaseQty method and in this method, we do increment the Quantity also update the Total Amount. Same like this when user click on down icon we do call DecreaseQty method to do in reverse order to decrement the quantity along with updating the Total Amount.
void IncreaseQty()
                   {
                       if (SD.Qty > 0)
                       {
                           SD.Qty = SD.Qty + 1;
 
                           SD.TotalAmount = initialPrice * SD.Qty;
 
                       }
 
                   }
 
 
                   void DecreaseQty()
                   {
                       if (SD.Qty > 1)
                       {
 
                           SD.Qty = SD.Qty - 1;
                           SD.TotalAmount = initialPrice * SD.Qty;
                       }
                   }

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.

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

Shopping Order Items


In the home page we bind the users shopped details with Item Name, Image, Order Date, Ordered Quantity and total amount. Users can also cancel the Order from the home page. When user click on the Cancel Order we delete the shopping order details from the table. 
@if (myShopList == null)
                {
                    <p><em>Loading...</em></p>
                }
                else
                {
  
                    @foreach (var myShoppings in myShopList)
                    {
                        <table>
                            <tr>
                                <td>
  
  
                                    <table class="divContainer">
                                        <tr>
                                            <td align="left" width="112px">
                                                <span style="color:#9F000F">
                                                    <img src="@myShoppings.ImageName" style="height:110px;width:110px" />
                                                </span>
                                            </td>
                                            <td align="left" valign="top">
                                                <table>
                                                    <tr>
                                                        <td valign="top">
                                                            <h2 style="color:#244f2b">@myShoppings.ItemName </h2>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            Order Date : @myShoppings.ShoppingDate.Value.ToString("yyyy-MM-dd HH:mm")
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            @myShoppings.Description
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td>
                                                            <h3 style="color:#ff0000">  @myShoppings.TotalAmount (INR) /  @myShoppings.Qty (QTY)</h3>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                            <td>
                                                <h3>
                                                    <button type="submit" class="btn btn-danger" onclick="@(async () => await deleteConfirm(@myShoppings))" style="width:220px;">
                                                        <img src="Images/delete.png"  /> Cancel Order
                                                    </button>
                                                </h3>
                                            </td>
                                        </tr>
  
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td style="height:10px;">
                                       
                                </td>
                            </tr>
                        </table>
                    }
                }
 In 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.
@functions {
        string UserName = "Shanu";
        ShoppingDetails SD = new ShoppingDetails();
        string Messages = "";
        myShopping[] myShopList;
        int shopID = 0;  
protected override async Task OnInitAsync()
        {
            shopID = 0;
            myShopList = await Http.GetJsonAsync<myShopping[]>("/api/ShoppingDetails/");
        }

 Cancel Order

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 “ 

@if (Messages != "")
{
<div id="outPopUp" style="position: absolute;  width: 552px;  height: 320px;  z-index: 15;  top: 38%;  left: 50%;  margin: -100px 0 0 -150px;  background: #fbde5a;">
    <div id="outPopUp" style="position: absolute;  width: 551px;  height: 248px;    background: #fc3a2e;">
        <img src="Images/C1.png" onclick="@closeMessage" />
        <span style="color:#ECF3F4;font-size:xx-large;display: inline-block;    margin: 10px 10px 0 0;   padding: 5px 10px ">
            @Messages
        </span>
    </div>
    <div id="outPopUp" style="position: absolute; top:260px; width:350px;left:24%; height: 70px; ">
        <h3>
            <button type="submit" class="btn btn-success" onclick="@(async () => await deleteShopping())" style="width:150px;">
                <img src="Images/tick.png" height="32px" width="32px"/>   Ok
            </button>
            <button type="submit" class="btn btn-danger" onclick="@closeMessage" style="width:150px;">
                <img src="Images/delete1.png" height="32px" width="32px"/>  Cancel
            </button>
        </h3>
    </div>
</div>
    }
  
   protected async Task deleteConfirm(myShopping sds)
        {
  
            shopID = sds.ShopId;
            Messages = "Are you Sure to Cancel your " + sds.ItemName + " Order ?";
        }
If user click on ok button we call the deleteShopping method and in this method, we delete the ShoppingDetails by the selected Shopping ID.If user click on Cancel button then we hide the Confirmation message and cancel deleting the Shopping order.
protected async Task deleteShopping()
        {
  
            await Http.DeleteAsync("/api/ShoppingDetails/" + Convert.ToInt32(shopID));
            Messages = "";
            myShopList = await Http.GetJsonAsync<myShopping[]>("/api/ShoppingDetails/");
        }  
  
        void closeMessage()
        {
            shopID = 0;
            Messages = ""
        }

Navigation Menu

 

Now we need to add this newly added Orders Razor page to our left Navigation. For adding this Open the Shared Folder and open the NavMenu.cshtml page and add the menu.

<li class="nav-item px-3">
            <NavLink class="nav-link" href="" Match=NavLinkMatch.All>
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="Orders">
                <span class="oi oi-plus" aria-hidden="true"></span> Orders Master Detail
            </NavLink>
        </li>

Conclusion

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

See Also

Download

Let's learn to make Shopping Cart using ASP.NET Core Blazor using EF and Web API