Skip to content

Commit

Permalink
Demo checkboxes for bool property on list
Browse files Browse the repository at this point in the history
  • Loading branch information
dahlbyk committed Sep 28, 2023
1 parent ed09a05 commit 0641f54
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Pages/Demos/Checkboxes.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,24 @@
}
</div>

<div class="form-field">
<p>
It's also common to bind a boolean property from a list to checkboxes.
</p>
@for(var i = 0; i <Model.Numbers.Count; i++) {
var number = Model.Numbers[i];

<label>
<input type="checkbox" asp-for="Numbers[i].IsSelected" />
@number.Name
</label>
<input type="hidden" asp-for="Numbers[i].Name" />
@* hidden for IsSelected is added automatically *@
}
<span asp-validation-for="Numbers"></span>
<em class="results">Selected numbers: @string.Join(", ", Model.Numbers.Where(n => n.IsSelected).Select(n => n.Name))</em>
</div>

<input type="submit" value="Submit"/>
</form>
</fieldset>
Expand Down
16 changes: 16 additions & 0 deletions Pages/Demos/Checkboxes.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ public class Checkboxes : PageModel
{
public string? StatusMessage { get; set; }

public void OnGet()
{
Numbers.Add(new() { Name = "One" });
Numbers.Add(new() { Name = "Two" });
Numbers.Add(new() { Name = "Three" });
}

public IActionResult OnPost()
{
StatusMessage = "Form was submitted: " + (ModelState.IsValid
Expand Down Expand Up @@ -36,4 +43,13 @@ public class InputModel
{
public bool IsChecked { get; set; }
}

[BindProperty]
public List<Selectable> Numbers { get; } = new();

public class Selectable
{
public required string Name { get; set; }
public bool IsSelected { get; set; }
}
}

0 comments on commit 0641f54

Please sign in to comment.