Hello, Habr! I continue to do online store on Blazor. In this part Iβll talk about how I added the ability to add goods to the basket. For details, welcome to cat.Content
References
β Sourcesβ Images on the Docker RegistryThe code
In the ProductsModel model added a field for the number of products in the basket. public int ItemsInBasketCount { get; set; }
In ProductsViewModel added:To check the display of pop-ups and check the status of user authentication. [Inject]
public AuthenticationStateProvider AuthStateProvider { get; set; }
[Inject]
public IJSRuntime Js { get; set; }
To get the current number of items in the basket. private async Task LoadItemsInBasketCount()
{
var (res, err) = await Repository.GetItemsInBasketCount();
if (!string.IsNullOrWhiteSpace(err))
{
Model.HandledErrors += $";{err}";
}
else
{
Model.ItemsInBasketCount = res;
}
}
Check authentication status. private async Task<bool> IsAuth()
{
var state = await AuthStateProvider.GetAuthenticationStateAsync();
return state?.User?.Identity?.IsAuthenticated ?? false;
}
Adding product to cart. public async Task AddToBasket(Guid productId)
{
Model.IsLoaded = false;
if (!await IsAuth())
{
await Js.InvokeVoidAsync(
"alert",
" . ."
);
Model.IsLoaded = true;
return;
}
var (r, e) = await Repository.AddToBasket(productId);
Model.HandledErrors = e;
Model.IsLoaded = true;
await LoadItemsInBasketCount();
}
In Products.razor Added:To display the number of products in the basket.<AuthorizeView>
<Authorized>
: @Model.ItemsInBasketCount
</Authorized>
</AuthorizeView>
To add an item to the cart.<td>
<input type="button"
value=" "
class="btn btn-success"
@onclick="@(async x=> await AddToBasket(product.Id))" />
</td>
Angular Version
