S.Rotenberg
S.Rotenberg

Reputation: 16

Bind value in Blazor application only if button is clicked

I am new to Blazor so I am not sure if this supported or I will have to use JS for it.

I have got an input field bound to a C# field in a Blazor application

<input type="text" name="name" value="@someField"/>

and a button:

< button type="button" @onclick="UpdateSomeField"/>

What I want to achieve is, only when the button is clicked the C# field someField should be updated with the value of the input field.

Any idea how this can bed done?

UPDATE

The UpdateSomeField Method should take value of the input field and update the Database and update the DOM with it (ex. in a table)

@code{
  private string someField;

  private void UpdateSomeField(){
    someField = //value of input field
    // Update Database
  } 
} 

Upvotes: 0

Views: 2010

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30001

To (specifically ) answer your question, you can do this:

<input type="text" name="name" value="@_someField" />

<button type="button" @onclick="UpdateSomeField"/>

@code {

    private string _someField;

    private string someField;

    private void UpdateSomeField()
    {
        someField = _someField;
        // Update Database
    }
}

For your code to access the value in the input, it must be bound to a field in your component. So if you don't want to set someField until you click on the button, you need an intermediate field to hold the input value.

[Polite] It seems to be a pretty silly way of doing it, but if that's what you want to do, it's your project.

Upvotes: 1

Related Questions