How is currentStar always changes its value even thogh its should be the same value as i, please How

Copper Contributor

Hi 

I have the following code written in Blazor I wrote it following this tutorial dot net learn but I didn't understand how the value of currentStar is changed when I click this span 

 

 

<span class="btn btn-danger"@onclick="(e => SubmitRating(currentStar))"></span>

 

 

but when I use the same code use i instead of currentStar the value sent to the SubmitRating() function is always 6 it does not change according to the span I click e.g when I click the first span displayed by the loop using the variable currentStar in the @onclickevent the value submitted to the SubmitRating() is 1 but when using the variable i instead the value submitted to the SubmitRating() is always 6
this is the code below and please watch the video linked up to understand clearly what I am trying to say.

 

 @for (int i = 1; i < 6; i++)
                    {
                        int currentStar=i;
                        
                        if (i <= currentRating)
                        {
                            <span class="btn btn-dark" id="@i" name="@currentStar" @onclick="(e => SubmitRating(currentStar))"></span>
                        }
                        else
                        {
                            <span class="btn btn-danger" id="@i" name="@currentStar" @onclick="(e => SubmitRating(i))"></span>
                        }
                    }

@code {
    Paiza selectedProduct;
    string selectedProductid;
    void selectProducts(string id)
    {
        selectedProductid = id;
        selectedProduct = Productservis.GetProducts().First(x => x.Id == id);
        GetCurrentRating();
    }

    int currentRating = 0;
    int voteCount = 0;
    string voteLabel;

    void GetCurrentRating()
    {
        if (selectedProduct.Ratings == null)
        {
            currentRating = 0;
            voteCount = 0;
        }
        else
        {
            voteCount = selectedProduct.Ratings.Count();
            voteLabel = voteCount > 1 ? "Votes" : "Vote";
            currentRating = selectedProduct.Ratings.Sum() / voteCount;
        }

    
    }

    void SubmitRating(int rating)
    {
      
        Productservis.AddRating(selectedProductid, rating);
        selectProducts(selectedProductid);
    }
}

 

 

1 Reply

Hi @jhonser77,

Thanks for posting your issue here.

However this platform is used for how-to discussions and sharing best practices for building any app with .NET.Since your issue is a technical question, welcome to post it in Microsoft Q&A forum, the support team and communities on Microsoft Q&A will help you for any technical questions.
Besides, it will be appreciated if you can share it here once you post this technical question Microsoft Q&A.
Best Regards,
Lan Huang