Search code examples
blazorblazor-webassemblymudblazor

Structure references to elements in loops in Blazor


Imagine I have an input field and a button and when I click the button, I want an overlay to appear. Easy. (this code is meant to illustrate the situation and may not compile)

<MudOverlay Visible="isThinking" DarkBackground="true">
    <MudProgressCircular Indeterminate="true" />
</MudOverlay>
<MudTextField></MudTextField>
<MudButton OnClick="SaveItem">Start</MudButton>

(inside the "SaveItem" function I will set "isThinking" to "true")

Now imagine the same thing inside a loop of items.

@foreach (var item in items)
{
    <MudOverlay Visible="isThinking" DarkBackground="true">
        <MudProgressCircular Indeterminate="true" />
    </MudOverlay>
    <MudTextField @bind-Value="item.Text"></MudTextField>
    <MudButton OnClick="@(async () => await SaveItem(item))">Start</MudButton>
}

My question is how should I identify the correct "MudOverlay" when the button is clicked? I cannot just use isThinking because it would activate the MudOverlay on every item.

My best idea so far is to put a Dictionary<string, bool> isThinkingList where I keep the isThinking status for each loop and then I use Visible="@(isThinkingList[item.Id])"

I highly doubt the Dictionary approach is the established best practice, hence this question. Hoping for your help. Thank you.


Solution

  • The easiest way is to have item.IsThinking.

    When item is a ViewModel then there is no problem. Otherwise, make (it) a ViewModel.