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 @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 @onclick="(e => SubmitRating(currentStar))"></span>
}
else
{
<span @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);
}
}
`
I tried logging both variables but the value rendered in HTML is the same.
if (i <= currentRating)
{
<span id="@i" name="@currentStar" @onclick="(e => SubmitRating(currentStar))"></span>
}
else
{
<span id="@i" name="@currentStar" @onclick="(e => SubmitRating(i))"></span>
}
CodePudding user response:
Please try this:
<span id="@i" @onclick='(() => SubmitRating(i))'></span>
CodePudding user response:
Variable i is incremented when the Razor component code is evaluated to be rendered and is always 6. That's why you have line:
int currentStar=i;
To store intermidiate value of i
Please see my answer