如何从 select 选项中获取值,同时使用 @onchange 执行功能。 (blazor)

How to get value from select option and at the same time use @onchange to do a function. (blazor)

<select @bind="Project.Supplier" @onchange="LoadProjectTypes">
   <option value="0">Select Supplier</option>

   @foreach (var supplier in ProjectSuppliers)
    {
        <option>@supplier.SupplierName</option>
    }
</select>

@code{
private ProjectModel Project;
private List<ProjectSuppliersModel> ProjectSuppliers;

public void CreateProject()
{
    //a function to insert the current project in the database
}

protected override void OnInitialized()
{
    ProjectSuppliers = _db.GetProjectSuppliers();
}

I want to get the selected Project.Supplier from select-option and then sent it to the data base. at the same time I want to use LoadProjectTypes function. but there is an error in the select element like this: "The attribute 'onchange' is used two or more times for this element". How can I solve it. Am I missing something? to be more clear: the function LoadProjectTypes affect another select element to show project types which is related just to the selected project supplier as its options

在幕后,@bind 使用@onchange 来设置您的变量,因此您不能同时使用两者。

我认为您通常不需要下拉菜单的双向绑定,所以我推荐下面的“未绑定”示例。但是如果你真的想做双向绑定,那么你可以在自定义 get; set; 中捕获变量的值变化,而不是试图捕获实际事件。

@page "/onchange"

<select @onchange="HandleOnChangeUnbound">
    <option disabled selected>Select an option</option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>
<br />
@if (UnboundSelected is not null)
{
    <div>@UnboundSelected</div>
}
<select @bind="BoundSelected">
    <option disabled selected>Select an option</option>
    <option>Option A</option>
    <option>Option B</option>
    <option>Option C</option>
</select>
@if (DisplayBound is not null)
{
    <div>@DisplayBound</div>
}



@code {
    string UnboundSelected { get; set; }
    string DisplayBound { get; set; }
    private string _boundSelected;
    public string BoundSelected
    {
        get
        {
            return _boundSelected;
        }
        set
        {
            _boundSelected = value;
            HandleOnChangeBound(value);
        }
    }
    void HandleOnChangeUnbound(ChangeEventArgs args)
    {
        UnboundSelected = args.Value.ToString();
        // Do DB stuff.
    }
    void HandleOnChangeBound(string value)
    {
        DisplayBound = value;
        // Do DB stuff
    }
}