Search code examples
c#.netblazor

Select Control Set Initial Value


We know that with InputSelect we cannot use both @bind-value and @onchange...

But if we use the latter (with select instead InputSelect), how can we set a initial value different from the first ? (eg. in this sample set to 2018, the value of a variable)

Something like if (i == month) => selected

<select @onchange="ChangeYear">
    @for (int i = 2015; i < DateTime.Now.Year + 1; i++)
    {
        <option value="@i">@i</option>
    }
</select>

@code {

    int year = 2018;

    void ChangeYear(ChangeEventArgs e)
    {
        int year = Convert.ToInt32(e.Value.ToString());

        //...
    }
}

Solution

  • You can implement it in a variety of ways, as for instance, define a local variable SelectedYear that is bound to the value property of the select element, and a change event that update the SelectedYear. This actually creates a two-way data binding.

    Note that SelectedYear is assigned a default value 2018

    <select value="@SelectedYear" @onchange="ChangeYear">
        @for (int i = 2015; i < DateTime.Now.Year + 1; i++)
        {
            <option value="@i">@i</option>
        }
    </select>
    
    <p>@SelectedYear</p>
    
    @code
     {
        private int SelectedYear { get; set; } = 2018;
    
        void ChangeYear(ChangeEventArgs e)
        {
            SelectedYear = Convert.ToInt32(e.Value.ToString());
    
        }
    }
    

    We know that with InputSelect we cannot use both @bind-value and @onchange

    This is because the compiler add the change event handler to update the Value (Note that it is @bind-Value, not @bind-value) property of the InputSelect component to the newly selected value. This is why you could have done something like this:

    <p>@SelectedYear</p>
    
    <EditForm Model="@employees">
        <DataAnnotationsValidator />
         <div>   
            <InputSelect @bind-Value="SelectedYear" Id="SelectedYear" Class="form-control">
                @for (int i = 2015; i < DateTime.Now.Year + 1; i++)
                {
                    <option value="@i">@i</option>
                }
            </InputSelect>
    
    
        </div>
        <button type="submit">Ok</button>
    
    </EditForm>
    
    @code
     {
        private string SelectedYear { get; set; } = "2018";
    
        public List<Employee> employees = new List<Employee>();
    
    
        public class Employee
        {
            public int YearBorn { get; set; }
            public string Name { get; set; }
        }
    }