gpt4 book ai didi

onchange - blazor editform 更改事件

转载 作者:行者123 更新时间:2023-12-05 08:15:19 24 4
gpt4 key购买 nike

我想在绑定(bind)到模型值的 blazor editform 中有一个 InputSelect,并且还有一个 onchange 事件,该事件根据新值更改模型中的其他属性。

绑定(bind)到@bind-Value 和@onchange 都不起作用(我猜是因为绑定(bind)值同时使用输入的值和值更改的属性。

我可以绑定(bind)到oninput,但我想知道是否有更好的方法来做到这一点。

<InputSelect id="inputPeriod" name="inputPeriod" class="form-control" @bind-Value="model.Period" @oninput="periodChanged">


protected void periodChanged(ChangeEventArgs e)
{}

我可以像这样绑定(bind)到oninput

但理想情况下,我想在更新模型属性后绑定(bind)到 @onchange 事件,或者知道最佳实践是什么。如果不使用绑定(bind)值,模型验证将不起作用,所以我能想到的唯一替代方法是让更改事件在我的模型的属性内部工作,但这似乎是错误的

最佳答案

这是一个愚蠢的示例,您必须在其中输入您的名字,然后选择您的宠物,结果是以您亲爱的宠物为您重命名。该示例描述了如何在字段更改时操作模型:

<EditForm EditContext="@EditContext">
<DataAnnotationsValidator />

<div class="form-group">
<label for="name">Enter your Name: </label>
<InputText Id="name" Class="form-control" @bind-Value="@person.Name"></InputText>
<ValidationMessage For="@(() => person.Name)" />

</div>
<div class="form-group">
<label for="body">Select your pet: </label>
<InputSelect @bind-Value="@person.Pet">
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Horse">Horse</option>
<option value="Lion">Lion</option>
</InputSelect>
<ValidationMessage For="@(() => person.Pet)" />
</div>

<p>
<button type="submit">Submit</button>
</p>
</EditForm>


@code
{
private EditContext EditContext;
private Person person = new Person();


protected override void OnInitialized()
{
EditContext = new EditContext(person);
EditContext.OnFieldChanged += EditContext_OnFieldChanged;

base.OnInitialized();
}

// Note: The OnFieldChanged event is raised for each field in the model
private void EditContext_OnFieldChanged(object sender, FieldChangedEventArgs e)
{
if (e.FieldIdentifier.FieldName == "Pet")
{

person.Name = person.Pet;

}
}


public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public string Pet { get; set; }
}
}

the only alternative way I can think of is to have the change events working inside the properties in my model, but that seems wrong

一点也不...

没有要求模型实现 INotifyPropertyChanged,但如果它们实现了,您可以轻松地将其连接到 EditContext。这样您就无需使用内置的 Input* 组件 - 您可以改为绑定(bind)到常规 HTML 元素并仍然获得修改通知。这为 UI 的呈现方式提供了更大的灵 active ,但代价是模型类中的复杂性和样板代码更加复杂。

希望这有助于...

关于onchange - blazor editform 更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61576373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com