Skip to content

Commit

Permalink
Merge pull request #72 from haacked/gh71
Browse files Browse the repository at this point in the history
Add demo checkboxes for `bool` property on list
  • Loading branch information
haacked authored Sep 29, 2023
2 parents ed09a05 + 225c52a commit 61d84ea
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Pages/Demos/Checkboxes.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,26 @@
}
</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>
@* The asp-for above appends an input with value="false" to the form. *@
@* An explicit hidden generates input with value="False": *@
@* <input type="hidden" asp-for="Numbers[i].IsSelected" /> *@
<input type="hidden" asp-for="Numbers[i].Name" />
}
<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 61d84ea

Please sign in to comment.