C#C
C#3y ago
Ryme

✅ Two-way binding class object Blazor Server

I seem to lack understanding of how to two-way bind a class to a child component that's updating some of the properties of the class.

Clicking the Update button will make the value change because StateHasChanged(), but this also makes the all the initialization methods run as well which in my real example is getting some data from a database and would be unnecessary to repeat.

I'm guessing this is exepcted behaviour since the object reference doesn't change?
Is there a way to get this working when only exposing a @bind-Value from the child component?

What would be the appropriate way to do this?

// Person.cs

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}


// Index.razor

@page "/"

<h1>Hello, @_person.Name! You are @_person.Age years old.</h1>

<PersonForm @bind-Value="_person" />
<button @onclick="StateHasChanged">Update</button>

@code {
    private Person _person = new() { Name = "Joe", Age = 40 };
}


// PersonForm.razor

<EditForm Model="BoundValue">
    <InputNumber @bind-Value="BoundValue.Age" />
    <InputText @bind-Value="BoundValue.Name" />
</EditForm>

@code {
    [Parameter]
    public Person Value { get; set; }

    [Parameter]
    public EventCallback<Person> ValueChanged { get; set; }

    private Person BoundValue
    {
        get => Value;
        set => ValueChaged.InvokeAsync(value);
    }
}
Was this page helpful?