Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add demo checkboxes for bool property on list #72

Merged
merged 1 commit into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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; }
}
}