Blazor: set initial value to a select using onchange and not bind

别来无恙 提交于 2021-02-10 17:35:46

问题


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

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());

        //...
    }
}

Thanks


回答1:


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; }
    }
}


来源:https://stackoverflow.com/questions/59444109/blazor-set-initial-value-to-a-select-using-onchange-and-not-bind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!