Our latest


Announcements, Blogs, Releases and much much more...

  • Read our latest news and announcements, hot off the press.

Announcements






Category Blazor FAQ

Published on 12-May-2021

How do I get two-way binding in Blazor with the Select component?
How do I get two-way binding in Blazor with the Select component?
How do I get two-way binding in Blazor with the Select component?

To use two-way binding in a Blazor component, add the bind attribute to a field. Two-way data binding pushes the changes to the component, gets the data from the component end, and updates its own data accordingly.

In the following example, we created a Select component and implemented two-way binding to the parent component.


Create a Select component in the Pages folder.

[SelectComponent.razor]

<div>
    <select id="Item" class="form-control-sm" @bind="@ListItem">
        @foreach (var list in SelectList)
        {
            @if (ListItem != null && String.Equals(list, ListItem, StringComparison.OrdinalIgnoreCase))
            {
                <option selected value="@list">@list</option>
            }
            else
            {
                <option value="@list">@list</option>
            }
        }
    </select>
</div>

@code {
    public IEnumerable<string> SelectList = new List<string>()
    {
        "List 1",
        "List 2",
        "List 3",
        "List 4",
        "List 5"
     };

    private string listItem { get; set; }

    [Parameter]
    public string ListItem
    {
        get { return listItem; }
        set {
            if (listItem != value)
            {
                listItem = value;
                if (ListItemChanged.HasDelegate)
                {
                    ListItemChanged.InvokeAsync(value);
                }
            }
        }
    }

    [Parameter]
    public EventCallback<string> ListItemChanged { get; set; }
}

Now define the Select component to in the Index.razor page and implement the two-way binding using the @bind attribute.

[Index.razor]

@page "/"

<div>
    <label>Bind Value</label>
    <input type="text" @bind="@Content" @bind:event="oninput" />
    <p>@Content</p>
</div>

<div>
    <SelectComponent @bind-ListItem="@Content" />
</div>

@code {
    [Parameter]
    public string Content { get; set; } = string.Empty;

}


Created on 12-May-2021 Last updated 23-May-2021

Assigned Tag
  • Blazor
  • FAQ