xcelm
xcelm

Reputation: 561

Passing data to Layout Razor Pages without controller

I would like to visualize data from my model in my layout page - specifically when user adds an item to the shopping cart I would like to count number of items in the shopping cart and display it in the navbar next to the image of shopping cart.

User can add the product from more then 1 page (e.g. from Index page, or Product/index page etc.).

Anyone dealt with something similar?

I would like my navbar to look like this :

Navbar

<div class="navbar-collapse collapse show" id="navbarColor01" style="">
    <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
            <a asp-page="/Index" class="nav-link" >Home <span class="sr-only">(current)</span></a>
        </li>
        <li>
            <a asp-page="/ShoppingCart/Index"> <i class="fas fa-shopping-cart fa-1x fa-cog "></i></a>
<div class="badge badge-danger badge-pill">5</div> //here is the number to be displayed
        </li>
    </ul>
</div>

Upvotes: 0

Views: 427

Answers (1)

Hameed
Hameed

Reputation: 1615

There are different ways to achieve this, evaluate your options then decide what to do.

You can achieve this by:

  1. Using view bags. This would cause code reputation throughout your project. Because you are going to set the view bag for each page visit.
  2. Using partial views. By calling Ajax request to the action, and then return partial view. Partial views usually intended to be part of the Controller/Page, which wouldn't make sense to have GetCart from different controller/page. Also it is best for avoiding view reputation.
  3. View Component. This is usually the ideal way to do it, since you need to do work behind the scene then return the value. View Components can live in their own, which is good for SoC.

My personal recommendation would be View Component, it is a new feature in asp.net core (replacing ChildAction).

Upvotes: 2

Related Questions