Last active
August 9, 2023 21:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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