Search code examples
asp.net-core-mvcblazorrazor-pagesblazor-webassemblyrazor-components

Asp.net core RazorComponent working with dynamic <li></li>


I am creating a RazorComponent in my asp.net core mvc application.

The component has a html list in it which is dynamically generated according to the number of item fetched from the model.

<ul>
   @{
     foreach (var prod in newProductList)
      {
        if (prod.Brand.Equals("1") && prod.Class.Equals("2"))
         {
           <li @onclick="(() => AddToSaleList(prod.Product, prod.ProductId, prod.SellRate))">
              <div class="posSelected-item">
                 <span class="posFoodname inline-block"> @prod.Product </span>
                 <span class="inline-block posSeletedPrice">@prod.SellRate</span>
                 <span class="posFoodtotal-item inline-block">
                    <i class="inline-block fas fa-minus" @onclick="() => Quantity(2)"></i>
                    <span class="posincrementItem">@changeQuaitity</span>
                    <i class="inline-block fas fa-plus" @onclick="() => Quantity(1)"></i>
                 </span>
              </div>
            </li>
          }
        }
       }
</ul>

The UI looks like this (as expected)

List of items

The Problem

The Plus and Minus buttons on the UI are supposed to increment or decrement the quantity of each item on the list.

The function I have written is

int changeQuaitity = 0;
public void Quantity(int e)
{
    if (e == 1)
    {
        changeQuaitity++;
    }
    else if (e == 2)
    {
        changeQuaitity--;
    }
}

However, as you can see since the increment is bound with the parameter changeQuantity so clicking on any of the Plus or Minus button changes the quantity of each list item simultaneously.

How do I modify the code to identify one list item and change quantity of only that item when the button on the list is clicked.


Solution

  • You need a separate counter for each entry, so I recommend making what I call a "carrier class" to carry quantity info along with each item:

    class countableProducts {
        Product prod {get; set;}
        int quantity;
    }
    

    In your initialization:

    foreach (var item in newProductList) 
        countableProductsList.Add( new countableProduct() { prod = item });
    

    Then in your loop

    foreach (var item in countableProductsList){
         // everything looks like item.prod.(property)
         <i class="inline-block fas fa-minus" @onclick="() => item.quantity--;"></i>
         <span class="posincrementItem">@item.quantity</span>
         <i class="inline-block fas fa-plus" @onclick="() => item.quantity++;"></i>
    }
    

    I don't have enough of your code to make a working example without basically writing the whole program, but hopefully you can see my idea.