Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Control Set Initial Value

Tags:

c#

.net

blazor

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

        //...
    }
}
like image 988
SandroRiz Avatar asked Dec 22 '19 12:12

SandroRiz


2 Answers

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; }
    }
}
like image 165
enet Avatar answered Oct 19 '22 08:10

enet


In HTML 'selected' is an attribute of the option. Blazor lets you toggle that with a boolean:

<option value="@i" selected="@(i==year)">@i</option>

The rest of your code can stay as-is.

like image 2
Henk Holterman Avatar answered Oct 19 '22 09:10

Henk Holterman