user2777546
user2777546

Reputation: 127

Dynamically binding input-field blazor

I'm trying to build a dynamic list of input field, while I choose the items from a multi select drop-down list. so how to dynamically bind variable to created text fields tied with the id's selected from the multi select drop-down list.

this is what I did .

<MudGrid>
   <MudItem xs="12" md="12">
        <MudSelect T="Parts" Label="US States" HelperText="Pick your favorite states" MultiSelection="true" @bind-Value="value" @bind-SelectedValues="options">
            @foreach (var part in parts)
            {
                <MudSelectItem T="Parts" Value="@part">@part.PartsValue</MudSelectItem>
            }
        </MudSelect>
    </MudItem>
    @foreach (Parts item in options)
    {
        int i = 0;
        <MudItem xs="3" sm="3" md="2">
            <MudTextField  @bind-Value="@xxxxx" Label="@item.PartsValue" Variant="Variant.Outlined" Margin="Margin.Dense"></MudTextField>
        </MudItem>
        i++;
    }
</MudGrid>

Upvotes: 0

Views: 1733

Answers (1)

henon
henon

Reputation: 2528

I made your code work and created a fiddle that allows you to execute it online: https://try.mudblazor.com/snippet/wYwFvcPUxSdgXHbW

<MudGrid>
   <MudItem xs="12" md="12">
        <MudSelect T="Part" MultiSelection="true" @bind-SelectedValues="options">
            @foreach (var part in parts)
            {
                <MudSelectItem T="Part" Value="@part">@part.PartValue</MudSelectItem>
            }
        </MudSelect>
    </MudItem>
    @foreach (var part in options)
    {
        <MudItem xs="3" sm="3" md="2">
            <MudTextField  @bind-Value="@part.PartValue" Label="Edit part" Variant="Variant.Outlined" Margin="Margin.Dense"></MudTextField>
        </MudItem>
    }
</MudGrid>

@code
{


    IEnumerable<Part> parts = new List<Part>()
    {
        new Part() {PartID = 1, PartValue = "Part 1"},
        new Part() {PartID = 2, PartValue = "Part 2"},
        new Part() {PartID = 3, PartValue = "Part 3"},
    };
    private IEnumerable<Part> options { get; set; } = new HashSet<Part>() { 
        new Part() {PartID = 3, PartValue = "Part 3"},
    };

    public class Part
    {
        public int PartID { get; set; }
        public string PartValue { get; set; }
        public override bool Equals(object o) {
            var other = o as Part;
            return other?.PartID==PartID;
        }
        public override int GetHashCode() => PartID.GetHashCode();        
        public override string ToString() {
            return PartValue;
        }
    }
}

Upvotes: 1

Related Questions