'Blazor Server Component - How to two way bind input html tag and call function onchange

I am trying to figure out how I can both two bind to an HTML input and call a function for the onchange event.

  <input id="nonce" type="hidden" @bind="@nonce" @onchange="Checkout" />

This gives the following error: The attribute 'onchange' is used two or more times for this element. Attributes must be unique (case-insensitive). The attribute 'onchange' is used by the '@bind' directive attribute.

One solution might be to not use the bind directive and instead use the onchange to update the value in the input.

Or can I override the onchange the @bind is using and add my own custom code?



Solution 1:[1]

One solution might be to not use the bind directive and instead use the onchange to update the value in the input.

This.

Depending on how you're using this, you might be able to do stuff in the get; set; for the property nonce as well, though technically trying to set a value doesn't guarantee that it's changing.

Solution 2:[2]

You should give the model value in OnInitialized method and then change it by @oninput event. Now, you can customize the @OnInputChange.

You can use the below code:

<input value="@Value" @oninput="@OnInputChange" />
<h4>@Value</h4>

@code {
BlazorRoom Room = new BlazorRoom
{
    Id = 1,
    Name = "Room 1",
    IsActive = true,
    Price = 499
    
};



public string Value { get; set; }

protected override void OnInitialized()
{
    base.OnInitialized();

    Value = Room.Name;
}


private void OnInputChange(ChangeEventArgs args )
{
    Value = (string)args.Value; 

    //you can customized it
    Value = Value.ToUpper();       
}
}

and the model is:

public class BlazorRoom
{
    public int Id { set; get; }

    public string Name { set; get; }

    public decimal Price { set; get; }

    public bool IsActive { set; get; }        
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bennyboy1973
Solution 2 Tom