Blazor:使用onchange将初始值设置为select而不绑定 [英] Blazor: set initial value to a select using onchange and not bind

查看:115
本文介绍了Blazor:使用onchange将初始值设置为select而不绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,使用InputSelect不能同时使用@ bind-value和@onchange

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

如果我们使用后者(用select代替InputSelect),我们如何设置一个不同于第一个的初始值?(例如,在此示例中,将变量的值设置为2018)

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)

类似于 if(i == month)=>已选择

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

        //...
    }
}

谢谢

推荐答案

您可以通过多种方式实现它,例如,定义绑定到select元素的value属性的局部变量SelectedYear,以及更改更新SelectedYear的事件.实际上,这将创建双向数据绑定.

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.

请注意,为SelectedYear分配了默认值2018

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

    }
}

我们知道,使用InputSelect不能同时使用@ bind-value和@onchange

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

这是因为编译器添加了更改事件处理程序,以将InputSelect组件的Value(请注意,它是@ bind-Value,而不是@ bind-value)属性更新为新选择的值.这就是为什么您可以这样做的原因:

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

这篇关于Blazor:使用onchange将初始值设置为select而不绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆