Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save divinci/de8324c365cea66696afa2845d93a2d7 to your computer and use it in GitHub Desktop.
Save divinci/de8324c365cea66696afa2845d93a2d7 to your computer and use it in GitHub Desktop.
Blazor OnClick Callback Argument Behavior
@page "/"
<h1>Blazor OnClick Callback Argument Behavior</h1>
<div class="row">
<div class="col-md-12">
Working
</div>
</div>
<div class="row">
@for (int i = 0; i < _stars.Length; i++)
{
// This is why it is working.
var starIndex = i;
<div class="col-md-1">
<span starIndex="@i" class="@_stars[i].CssClass" onclick="@((e) => OnClickStar(starIndex))"></span>
</div>
}
</div>
<div class="row">
<div class="col-md-12">
Not Working
</div>
</div>
<div class="row">
@for (int i = 0; i < _stars.Length; i++)
{
<div class="col-md-1">
<span starIndex="@i" class="@_stars[i].CssClass" onclick="@((e) => OnClickStar(i))">&nbsp;</span>
</div>
}
</div>
<div class="row">
<div class="col-md-12">
<pre>@Log</pre>
</div>
</div>
@functions
{
public class Star
{
public bool Checked { get; set; }
public string CssClass
{
get
{
return Checked ? "fa fa-star" : "far fa-star";
}
}
}
private StringBuilder _log = new StringBuilder();
public string Log
{
get
{
return _log.ToString();
}
}
public Star[] _stars = new Star[]{
new Star(){ Checked = false },
new Star(){ Checked = false },
new Star(){ Checked = false },
new Star(){ Checked = false },
new Star(){ Checked = false }
};
public void OnClickStar(int index)
{
_log.AppendLine($"{DateTime.Now.ToShortTimeString()} | OnClickStar called with index argument {index}");
for (int i = 0; i < _stars.Length; i++)
{
if (i <= index)
_stars[i].Checked = true;
else
_stars[i].Checked = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment