Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor TwoWay Binding on custom Component

I'm creating a blazor server side app and have problems to bind a value between two custom components.

I've looked through different example of how the bind or @bind is supposed to work but I cannot figure out what up to date information on this matter is.

Given a model class User:

public class User
    {
        [Mapping(ColumnName = "short_id")]
        public string ShortId { get; set; }

        public User()
        {

        }
    }

I want to build a form which displays all properties of this user and has them in an input so it can be edited and in the end saved to a database.

My Form (parent component) looks like this:

<div class="edit-user-form">
    <AnimatedUserInput TbText="@User.ShortId" Placeholder="MHTEE Id"/>
    <button class="btn btn-secondary" @onclick="Hide" style="{display:inline-block;}">Back</button>
    <button class="btn btn-primary" @onclick="SaveUser" style="{display:inline-block;}">Save</button>
</div>
@code {
    [Parameter] public vUser User { get; set; }

    [Parameter] public Action Hide { get; set; }

    bool _error = false;

    void SaveUser()
    {
        ValidateUserData();
    }

    void ValidateUserData()
    {
        _error = string.IsNullOrWhiteSpace(User.ShortId);
    }
}

Where AnimatedUserInput is a custom component that looks like this:

<div class="edit-area @FocusClass @WiggleClass">
    <input type="text" @bind="@TbText" />
    <span data-placeholder="@Placeholder"></span>
</div>
@code {
    [Parameter]
    public string TbText { get; set; }

    [Parameter]
    public string Placeholder { get; set; }
}

Now in the Input textbox I correctly see the ShortId of the User object in my parent component.

However if I change the text in the input and click on the Save button which triggers the ValidateUserData method and allows me to look at the current User object I see that no changes have been done in the actual User.ShortId property but only on the input.

Is there any way to bind it so that changes in the input will automatically be applied to the binded property?

I have several of these properies which need to be shown in the form which is why I dont want to hook a custom OnChanged Event for each of those properties.

like image 217
Drew Fyre Avatar asked Oct 02 '19 07:10

Drew Fyre


2 Answers

Ok so for anyone stumbling upon this. I tried a bit more and found a solution. So to my custom input component AnimatedUserInput I added a EventCallback which I call everytime the value on the input is updated:

@code {

    [Parameter]
    public string TbText
    {
        get => _tbText;
        set
        {
            if (_tbText == value) return;

            _tbText = value;
            TbTextChanged.InvokeAsync(value);
        }
    }

    [Parameter]
    public EventCallback<string> TbTextChanged { get; set; }

    [Parameter]
    public string Placeholder { get; set; }

    private string _tbText;
}

And the binding on my parent component looks like this:

<div class="edit-user-form">
    <AnimatedUserInput @bind-TbText="@User.ShortId" Placeholder="MHTEE Id"/>
    <AnimatedUserInput @bind-TbText="@User.FirstName" Placeholder="First name" />
    <AnimatedUserInput @bind-TbText="@User.LastName" Placeholder="Last name" />
    <AnimatedUserInput @bind-TbText="@User.UserName" Placeholder="Username" />
    <AnimatedUserInput @bind-TbText="@User.StaffType" Placeholder="Staff type" />
    <AnimatedUserInput @bind-TbText="@User.Token" Placeholder="Token" />
    <button class="btn btn-secondary" @onclick="Hide" style="{display:inline-block;}">Back</button>
    <button class="btn btn-primary" @onclick="SaveUser" style="{display:inline-block;}">Save</button>
</div>

@code {
    [Parameter] public vUser User { get; set; }
}

This way blazor can correctly bind the values together and updates them from both sides the way I would expect them to bind.

like image 84
Drew Fyre Avatar answered Oct 12 '22 22:10

Drew Fyre


Some of the Data binding resources out there for Blazor fail to mention that when you do @bind-Value you actually get auto mapping to 3 parameters:

Bind Call

<CustomComponent TValue="DateTime?" @bind-Value="order.PurchaseDate"></CustomComponent>

Custom Component

@using System.Linq.Expressions;
@typeparam TValue
//...
@code {
[Parameter]
public virtual TValue Value { get; set; }
[Parameter]
public EventCallback<TValue> ValueChanged { get; set; }
[Parameter]
public Expression<Func<TValue>> ValueExpression { get; set; }
//...
}

This is important to know if you want a component that simplifies a user interface, as you might need that Value Expression for form validation...

<ValidationMessage For="ValueExpression" ></ValidationMessage>

In a similiar sense, I use this ValueExpression accesor method to also run my label, as of course you might want a model data annotation, just like you might want to know if the field has a max length, or is required...

@( DisplayName.For(ValueExpression) )

Display Name For Code:

public static class StringHelpers
{
    public static string CamelCaseToPhrase(this string self)
    {
        return Regex.Replace(self, "([A-Z])", " $1").Trim();
    }
}

public static class DisplayName
{
    public static string For(string input)
    {
        return input.CamelCaseToPhrase();
    }

    public static string For<T>(Expression<Func<T>> accessor)
    {
        var expression = (MemberExpression)accessor.Body;
        var value = expression.Member.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
        return value?.Name ?? expression.Member.Name?.CamelCaseToPhrase() ?? "";
    }

}

I share this here because google lands me here when I search for this, and most of the other resources out there do a bad job of giving this full picture, so hopefully this helps others too. Especially if you want to access Data Annotations, that pattern was also included.

like image 44
Greg Avatar answered Oct 13 '22 00:10

Greg