Skip to content

Instantly share code, notes, and snippets.

@mkArtakMSFT
Last active August 9, 2023 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkArtakMSFT/b8f734317f4fa9474761bc7538d69b1f to your computer and use it in GitHub Desktop.
Save mkArtakMSFT/b8f734317f4fa9474761bc7538d69b1f to your computer and use it in GitHub Desktop.
This sample demonstrates how to use a single form with multiple actions in Blazor
<form @formname="updateTodos" method="post" @onsubmit="HandleSubmit">
<AntiforgeryToken />
@if (Items is not null)
{
@foreach (var (id, item) in Items)
{
<p>
<input type="checkbox" name="items[@id].IsDone" />
<input name="items[@id].Text" value="@item.Text" />
<button name="deleteItem" value="@id" type="submit">Delete @item</button>
</p>
}
<button type="submit">Update items</button>
}
<p>
Add item:
<input name="newItemText" placeholder="Type here..." />
<button name="addItem" type="submit">Add</button>
</p>
</form>
@code {
public class TodoItem
{
public bool IsDone { get; set; }
public string? Text { get; set; }
}
public static Dictionary<Guid, TodoItem> Items { get; set; } = new();
[SupplyParameterFromForm] public Guid? DeleteItem { get; set; }
[SupplyParameterFromForm] public string? AddItem { get; set; }
[SupplyParameterFromForm] public string? NewItemText { get; set; }
public void HandleSubmit()
{
if (DeleteItem.HasValue)
{
Items.Remove(DeleteItem.Value);
}
if (AddItem is not null && !string.IsNullOrEmpty(NewItemText))
{
Items.Add(Guid.NewGuid(), new TodoItem { Text = NewItemText });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment