Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

c# - How to make two-way binding on Blazor component

I want to create custom input, so I created this component:

MyInputComponent.razor:

<div>
  <input type="text" @bind="BindingValue" />
</div>

@code {
    [Parameter]
    public string BindingValue { get; set; }
}

Then the usage:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent BindingValue="model.Name" />
</EditForm>

@code {
    User model = new User() { Name = "My Name" };

    private void Submit()
    {
       // here I found model.Name = null;
   }
}

When I debug MyInputComponent, I found the value as I have entered. But when I submit the form, the value is null.

How to do it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quick answer

Quoting Blazor docs:

Component parameters

Binding recognizes component parameters, where @bind-{property} can bind a property value across components.

For your page:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent @bind-BindingValue="model.Name" />
</EditForm>

The child component MyInputComponent:

<div>
  <InputText type="text" @bind-Value="@BindingValue" />
</div>

@code {

    private string _value;

    [Parameter]
    public string BindingValue
    {
        get => _value;
        set
        {
            if (_value == value ) return;
            _value = value;
            BindingValueChanged.InvokeAsync(value);
        }
    }

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

}

Notice

  • You should to raise binding changes from children component through EventCallback<string> BindingValueChanged.
  • I chose BindingValue and BindingValueChanged as identifiers, but, you can use just Value and ValueChanged. Then will be: <MyInputComponent @bind-Value="model.Name" />

Try it at BlazorFiddle.

Edited: See Option 2 below for a clean solution:


Your control inside an EditForm

If you want to put your component inside an EditForm and deal with validations, or take other actions using the onchange event, you should to raise EditContext.NotifyFieldChanged. You have 2 options to do it.

Option 1: Raising from EditContext

You can get EditContext from CascadeParameter and invoke NotifyFieldChanged by hand:

    [CascadingParameter] EditContext EditContext { get; set; } = default!;
    [Parameter] public Expression<Func<string>>? ValueExpression { get; set; }
    #endregion

    #region bindedValue
    [Parameter] public EventCallback<string> ValueChanged { get; set; }
    private string _value { set; get; } = "";
    [Parameter]
    public string Value
    {
        get => _value;
        set
        {
            if (_value == value) return;
            _value = value;
            ValueChanged.InvokeAsync(value);
            var fieldIdentifier = FieldIdentifier.Create(ValueExpression);
            EditContext.NotifyFieldChanged(fieldIdentifier);

        }
    }

Option 2 (recomended): Through inheritance from InputBase

You can inherit from InputBase<string> and just implement TryParseValueFromString. InputBase will do the work for you,When you inherit from InputBase you have Value, ValueChanged, EditContext, etc.

protected override bool TryParseValueFromString(string? value, out string result, [NotNullWhen(false)] out string? validationErrorMessage)
{
    result = value ?? "";
    validationErrorMessage = null;
    return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...