I have a loop in .cshtml:
<form method="post" asp-page-handler="AddToCart">
@foreach (var product in Model.PopularProducts)
{
<article class="product">
<input type="hidden" name="productId" value="@product.Id" />
<div class="product-figure">
<button type="submit">Add To Cart</button>
</div>
<h5 class="product-title"><a href="product/@product.Id">@product.Name</a></h5>
</article>
}
</form>
and onpost method in code behind:
public IActionResult OnPostAddToCart(int productId)
{
var productInBasket = AddToCart(productId, 1);
return Redirect("/checkout");
}
but productId
is always = 1 (id of the first product). How can I get id of correct product?
Seems like I need to set some unique name for each input
<input type="hidden" name="productId" value="@product.Id" />
but then how can I get it from OnPost(parameter)?
You have all itens in the same form, so when you click any item of the form, they are all posted, then your method pickup the first one. Try create one form for each item.
@foreach (var product in Model.PopularProducts)
{
<form method="post" asp-page-handler="AddToCart">
<article class="product">
<input type="hidden" name="productId" value="@product.Id" />
<div class="product-figure">
<button type="submit">Add To Cart</button>
</div>
<h5 class="product-title"><a href="product/@product.Id">@product.Name</a></h5>
</article>
</form>
}