Reputation: 265
I have Blazor server app, and how can I dynamically add new input textboxes on button click and remove it and get the value of all the input textboxes on submit button click so that I can save them in the database.
@for (int i = count; i >= 1; i--)
{
<div class="row">
<input type="text" @bind-value="@text_val" /> <p>@i</p><p>@count</p>
</div>
}
<div class="row">
<button @onclick=@(() => Increment())>Add User</button>
</div>
@code {
public string text_val;
public int count = 1;
public void Increment()
{
count = count + 1;
}
}
Any help will be great. Thank you
Upvotes: 4
Views: 7089
Reputation: 4874
Initialize a list of values as I have done with the values
list here. I have added an Add Users button here and a method to be executed on click called AddValue()
which adds a new empty string to the list. This will trigger a state change and Blazor will automatically re-execute the for loop and add an additional text box.
The for loop adds an <input type="text">
for each item in the list and the @onchange
event will update the corresponding value in the list using the UpdateValue()
method when the value of the textbox changes and loses focus. If you want the value to update the textbox every time it changes without losing focus, use @oninput
instead.
I have also added a Remove button and a RemoveValue()
method to remove the textboxes and values.
You can access the values of the values
list in any method. When the Submit button is clicked, HandleSubmit()
will be called and you can access and validate the list/textbox values there.
If you are using a loop variable like i
that changes on every iteration in a lambda expression, make sure that you first copy it to a local variable. Otherwise, since the lambda expression will capture the variable i
, and when the lambda executes later, the latest value of i
will be used which after the end of the loop will be equal to the length of the list.
I have done this by copying i
first to a local variable index
here.
<div class="container border">
<h3>Users</h3>
<hr />
<button @onclick="AddValue" class="btn btn-primary">Add User</button>
@for (int i = 0; i < values.Count; i++)
{
int index = i;
<div>
<input type="text" @onchange="(e) => UpdateValue(index, e.Value.ToString())" value="@values[i]" />
<button @onclick="() => RemoveValue(index)" class="btn btn-outline-danger">Remove</button>
</div>
}
<hr />
<div>
<button @onclick="HandleSubmit" class="btn btn-success">Submit</button>
</div>
<hr />
@for (int j = 0; j < values.Count; j++)
{
<p>@values[j]</p>
}
</div>
@code {
private List<string> values = new List<string>();
private void AddValue() => values.Add("");
private void UpdateValue(int i, string value) => values[i] = value;
private void RemoveValue(int i) => values.RemoveAt(i);
private void HandleSubmit()
{
//Access and validate the values list here
}
}
See it working on BlazorFiddle.
Upvotes: 6