Hello,
New user here, a beginner trying to understand how checkbox asp-for works.
In this sample application, I am trying to toggle a checkbox on post by a button, but failing.
Having googled, read tutorials and attempted variations, I am still stuck.
Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<form method="post">
<input id="checkbox" asp-for="IsChecked" />
<label for="checkbox">asp-for = "IsChecked"</label>
<br />
<br />
<span>Model.IsChecked = @Model.IsChecked</span>
<br />
<br />
<input type="submit" value="IsChecked = !IsChecked" />
</form>
Index.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public bool IsChecked { get; set; }
public void OnPost()
{
IsChecked = !IsChecked;
}
}
}
Auto-generated
<input id="checkbox" type="checkbox" data-val="true" data-val-required="The IsChecked field is required." name="IsChecked" value="true">
<input name="IsChecked" type="hidden" value="false">
Issue:
When launched, checkbox is not checked and span shows False, as expected.
![1](https://learn-attachment.microsoft.com/api/attachments/bef1daa9-6ba0-4f67-9695-350c05f44af0?platform=QnA)
On submit the first time, span changes to True, hence OnPost works, yet checkbox remains unchecked.
![2](https://learn-attachment.microsoft.com/api/attachments/d09ce605-a245-4c55-ac20-a03136861d67?platform=QnA)
On further submits, span remains True and checkbox remains unchecked.
Question:
Why is checkbox never checked despite being bound to Model.IsChecked which OnPost successfully toggled to True as span shows? Sticking to using tag helpers, what am I missing to make it work?
Thanks in advance for any advice or direction.