我从SQL Server接收数据并将其加载到模型中:
namespace BlazorServer.Models
{
public class Animal
{
public int height { get; set; }
public string name { get; set; }
public string origin { get; set; }
}
}
在组件中,我使用模型来显示数据。用户可以编辑数据。这是一个示例:
<input @onchange="args => ValueChanged(args)" value="@animal.name" class="form-control form-control-sm border rounded" />
如何获取模型的哪个属性已更改?我尝试了以下操作,但只得到了新值:
private void ValueChanged(ChangeEventArgs args)
{
var newValue = args.Value;
}
我想更新组件中的模型(等于blazor的绑定(AND并立即将数据发送到SQL服务器。
Blazor附带了管理EditContext
的EditForm
,以及一组与EditContext
接口的输入控件(在您的情况下为InputText
(。您可以访问EditContext
,在OnFieldChanged
上注册事件处理程序并获取更改事件。您将获得一个FieldIdentifier
,您可以使用它来标识哪个字段已更改。
参见MS文档
这里有一个简单的剃刀页面,演示使用EditContext
和OnFieldChanged
@page "/Test"
@implements IDisposable
<EditForm EditContext="this.editContext" class="m-3">
Animal: <InputText @bind-Value="this.model.name"></InputText><br />
Origin: <InputText @bind-Value="this.model.origin"></InputText><br />
</EditForm>
<div class="m-3">FieldChanged:<i>@this.FieldChanged</i> </div>
@code {
public class Animal
{
public int height { get; set; }
public string name { get; set; }
public string origin { get; set; }
}
private Animal model = new Animal() { height = 2, name = "giraffe", origin = "Africa" };
private EditContext editContext;
private string FieldChanged = "none";
protected override Task OnInitializedAsync()
{
this.editContext = new EditContext(model);
this.editContext.OnFieldChanged += this.OnFieldChanged;
return base.OnInitializedAsync();
}
private void OnFieldChanged(object sender, FieldChangedEventArgs e)
{
var x = e.FieldIdentifier;
this.FieldChanged = e.FieldIdentifier.FieldName;
}
// Need to Implement IDisosable to unhook event handler
public void Dispose ()
{
this.editContext.OnFieldChanged -= OnFieldChanged;
}
}