asp.net core razor page checkboxes model binding (always false)

Viewed 1327

i have a razor page in asp.net core with the following input tag:

<input asp-for="chkPref" />

in the code-behind i have:

public bool chkPref { get; set; }

so when i run the app, i can confirm in Request.Form that I'm getting...

checkbox checked = {true,false}

checkbox unchecked = {false}

which is expected, according to https://www.learnrazorpages.com/razor-pages/forms/checkboxes (which seems to be the site everyone points to for answers to this issue)

however, that page states that the model binding will figure out that {true,false} is actually true but i'm getting false no matter what.

the website above alludes to the fact that this "just happens"...

If the checkbox is checked, the posted value will be true,false. The model binder will correctly extract true from the value. Otherwise it will be false.

but that doesn't seem to be working, or at least isn't that obvious how it works.

i'm not exactly sure how you can assign two values (ie - true, false) to a single bool in the first place.

i even tried turning it into a List<bool> but that didn't work either. that throws a whole different set of errors.

1 Answers

I believe looking at the Request.Form gives you the raw form data. What you probably want is to leverage form binder:

you can either mark propertes with BindPropertyAttribute or indicate you expect these specific properties as parameters to your OnPost handler (see example below).

Given a razor page

<form method="post">
    <input asp-for="chkPref" />
    @Html.CheckBoxFor(model => model.chkPref2)
    <button>Click</button>
</form>

your code-behind could look like so:

public class IndexModel : PageModel
{
    public bool chkPref { get; set; } // will not get bound

    [BindProperty] // Binder needs to know which properties to work with
    public bool chkPref2 { get; set; }

    public void OnPost(bool chkPref)// PageActionInvoker will pass correct value as parameter
    {
        this.chkPref = chkPref;
    }
}
Related