Create an E-Commerce Application in ASP.NET 5 MVC – Part 2

Create an E-Commerce Application in ASP.NET 5 MVC – Part 2

Follow Me Here

This part is a continuation of Part 1 where I have shown how to create a product cart in an e-commerce application. So I strongly suggest you go through that part first in order to have a complete understanding of the project.

Create a Cart Controller

In the Controllers folder, add an empty MVC controller by right-clicking Controllers folder and Add => Controller

On the ensuing Add New Scaffolded Item dialog, select MVC Controller-Empty and click Add

On the Add New Item dialog name it CartController and click Add

If you open the CartController created, you’ll see the following default code which we shall be editing in a bit.

 public class CartController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

Add the Helper Methods

At the project level, add a folder named Helpers.

Add the NewtonSoft.Json nuget package from Package Manager by right-clicking the project and clicking Manage NuGet Packages

Create a class named SessionHelper and put the following code in this class:

public static class SessionHelper
    {
        public static  void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default : JsonConvert.DeserializeObject<T>(value); 
        }
    }

The SessionHelper class SetObjectAsJson method sets the key and value for a session object as a Json string. On the other hand, the helper method GetObjectFromJson retrieves the object for a key after deserializing the Json string.

Edit the CartController

Now replace the CartController Index() action method code with the following snippet:

        public IActionResult Index()
        {
            var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            ViewBag.cart = cart;
            ViewBag.total = cart.Sum(item => item.Product.Price * item.Quantity);
            ViewBag.total = Math.Round(ViewBag.total, 2);
            return View();
        }

       private int isExist(string id)
        {
            List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            for (int i = 0; i < cart.Count; i++)
            {
                if(cart[i].Product.Id.Equals(id))
                {
                    return i;
                }
            }
            return -1; 
        }
       public IActionResult Buy(string id)
        {
            ProductModel productModel = new ProductModel();
            if (SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart") == null)
            {
                List<Item> cart = new List<Item>();
                cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            else
            {
                List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
                int index = isExist(id);
                if (index != -1)
                {
                    cart[index].Quantity++;
                }
                else
                {
                    cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
                }
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return RedirectToAction("Index");
        }

        public IActionResult Remove(string id)
        {
            List<Item> cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            int index = isExist(id);
            cart.RemoveAt(index);
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            return RedirectToAction("Index");

        }

Explaining the CartController Methods

The Index action sets a cart object in the session with the object it receives from the Session Helper class using HttpContext . It then sets a dynamic ViewBag object with the sum total price that it reads from the cart, rounding it to two decimal places and returns the view.

The isExist method checks each object in the cart with a given id and if the object exists, returns its index, otherwise it returns -1

Buy method looks for an item in the cart and if there are none, adds a new item to the cart using the Product id passed to it as a parameter and sets the added object as Json string to the session. If the cart contains any product, on the other hand, its index number is found and if the index does exist for the item, its quantity is incremented by one. If the index for the item is not found, the item is added as a new item to the cart and again it is added to the session as a Json string. The view is redirected to the Index action at the end.

Remove method looks for the index of the item to be removed from the cart and removes it from the cart (if it is found). It then updates the session with an updated Json string. Finally view is redirected to the Index action at the end.

Create the View for the CartController Index Action Method

Create an Empty Razor view for the Index Action method of the CartController and paste the following code to replace its default template code

@{ 
    Layout = "_Layout";
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
</head>
<body>
    <h3>Cart Page</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>Option</th>
            <th>Id</th>
            <th>Name</th>
            <th>Photo</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Sub Total</th>
        </tr>
        @foreach (var item in ViewBag.cart)
        {
        <tr>
            <tr>
                <td class="d-lg-table-cell"><a asp-controller="cart" asp-action="remove" asp-route-id="@item.Product.Id">Remove</a> </td>
                <td class="d-lg-table-cell">@item.Product.Id</td>
                <td class="d-lg-table-cell">@item.Product.Name</td>
                <td class="d-lg-table-cell"><img src="~/images/@item.Product.Photo" width="100" /> </td>
                <td class="d-lg-table-cell">@item.Product.Price</td>
                <td class="d-lg-table-cell">@item.Quantity</td>
                <td class="d-lg-table-cell">@(item.Product.Price * item.Quantity )</td>
            </tr>
        </tr>
        }
        <tr>
            <td align="right" colspan="6">Sum</td>
            <td>
                @ViewBag.total
            </td>
        </tr>
    </table>
    <br />
    <a asp-controller="product" asp-action="index">Continue Shopping</a>
    <a asp-controller="checkout" asp-action="index" asp-route-id="">Go To Checkout</a>
</body>
</html>

This view renders a Cart Page by iterating over all the Products passed to it from the cart assigned to the ViewBag (in the controller) and displaying the Product property values in HTML table cells in one-row per item. The table also displays the item price, quantity, and total sum of all the items in the cart. At the footer end, the page displays appropriate links to Continue Shopping or Go To the Checkout

Create the CheckOutController

Now create the CheckOutController following the steps for creating the CartController shown earlier and paste the following code to overwrite the existing code

        public IActionResult Index()
        {
            var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            ViewBag.cart = cart;
            ViewBag.total = cart.Sum(item => item.Product.Price * item.Quantity);
            ViewBag.total = Math.Round(ViewBag.total, 2);
            return View();
        }

As you can see, the Index action is the same as that in the CartController seen earlier. So finally, we shall have to create the View for this Index action to render the check out page.

Create the View for the CheckoutController Index action method

Create an Empty Razor view for the Index Action method of the CheckoutController and paste the following code to replace its default template code

@{ 
    Layout = "_Layout";
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
</head>
<body>
    <h3>Checkout Page</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th> Total Amount To Pay</th>
        </tr>
        <tr>
            <td class="d-lg-table-cell">
                @ViewBag.total
            </td>
        </tr>
    </table>
</body>
</html>

Startup Configuration

Now open the Startup class ConfigureServices method and add the following code above services.AddControllersWithViews();

          services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(20);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true; 

            });

In the Configure method of the Startup class add the following line below routing middleware to use session middleware as follows:

app.UseSession();

Running the Application

Click on IIS Express green arrow on top to run the application. If there are no errors the application will run and show the views as in the screenshots below

On clicking the Buy Now image to buy any of the flowers, it shows the screen below for the Cart Page

If you click Continue Shopping link, it takes back to the Product page where you could buy more

If you click Remove on any flower, it disappears say Id = 5, the cart will be updated as below

Finally if you click Go To Checkout it will show the following screen

Follow Me Here

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.