简体   繁体   中英

Blazor Custom Bind - Get Property of model that changed

I receive data from a SQL Server and load it into a model:

namespace BlazorServer.Models
{
    public class Animal
    {
        public int height { get; set; }

        public string name { get; set; }

        public string origin { get; set; }
    }
}

In a component I use the model to display data. The user is able to edit the data. Here is a sample:

<input @onchange="args => ValueChanged(args)" value="@animal.name" class="form-control form-control-sm border rounded" />

How do I get which property of the model has changed? I tried the following, but I only get the new value:

private void ValueChanged(ChangeEventArgs args)
{
    var newValue = args.Value;
}

I want to update the model in the component (which equals the binding of blazor) AND also send the data to the SQL server right away.

Blazor comes with EditForm which manages an EditContext , and a set of Input controls - InputText in your case - that interface with EditContext . You can access the EditContext , register an event handler on OnFieldChanged and get change events. You get passed a FieldIdentifier that you can use to identify which field has been changed.

See - MS Documentation

Here's a simple razor page that demos using EditContext and 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM