Home > Software design >  Blazor - Bind each element in @foreach loop to corresponding Array index
Blazor - Bind each element in @foreach loop to corresponding Array index

Time:04-10

I have a @foreach loop in my Blazor page which iterates through a boolean List. I would like a field to show up if the boolean is true. Then, I would like to bind the values inside the element to an item in a new string List. However, when I try to do it, the text inside the binds to all the items in my new List instead of just one. Below is my code:

@foreach (bool item in myList)
{
    if (item)
    {
        <input @bind="userInputBind[index]"/>
        if (index < 6) index  ;
    }
}

@code {
    public List<bool> myList = new List<bool> { false, false, true, false, true, false };
    public List<string> userInputBind = new List<string> { "", "" };
    public int index;
}

When I input "string1" into the first input field and "string2" into the second field, I expect the list to contain { "string1", "string2" }. Instead, both of the strings are "string2". How can I fix this issue? Any help is appreciated!

CodePudding user response:

This works. It uses a local loop variable to capture the "index" for each loop iteration, and resets index for each render.

@page "/"

@{index = 0;}
@foreach (bool item in myList)
{
    if (item)
    {
        int loopindex = index;
        <div>
        <input @bind="userInputBind[loopindex]"/>
        </div>
        index  ;
    }
}

@foreach(var value in userInputBind)
{
    <div >
        Value = @value
    </div>
}

@code {
    public List<bool> myList = new List<bool> { false, false, true, false, true, false };
    public List<string> userInputBind = new List<string> { "One", "Two" };
    public int index;
}

CodePudding user response:

Not sure what you're trying to achieve... The following, however, creates a single list of UserInput objects, each of which defines a boolean field to render an input element if its value is true, and a Text field that is bound to the input element shown.

@foreach (var item in items)
{
    @if (item.Shown)
    {
        <input @bind="item.Text" />
    }

}

@foreach (var item in items)
{
    <div>@item.Text</div>
  
}

@code {
    
    private IList<UserInput> items = new List<UserInput> { new UserInput { Shown = false },
    new UserInput { Shown = false },
    new UserInput { Shown = true },
    new UserInput { Shown = false },
    new UserInput { Shown = true },
    new UserInput { Shown = false }};

    public class UserInput
    {
        public bool Shown { get; set; }
        public string Text { get; set; }
    }
}
  • Related