Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

razor pages handler with checkbox boolean doesn't bind

I have a form with several inputs. I send the form per ajax with Jquery's form.serialize(). The network tab shows that the data is sent successfully (welcomesCritiques: on, complete: on).

On the server side I catch those inputs in a custom handler

public async Task<IActionResult> OnPostLoadBooksAsync(string search, bool welcomesCritiques, bool complete, int startIndex, int amount)

The string and the ints bind perfectly fine. But the bools are always false. When I replace the bools with a string, I get "on".

Is this a known issue? How can I make "on" become a bool?

Thanks for your help!

like image 630
Doidel Avatar asked Jun 07 '26 22:06

Doidel


1 Answers

To bind to a boolean, you need to set the value to "true", not the default, which is "on":

<input type="checkbox" name="welcomesCritiques" value="true" />

The value will only be submitted if the checkbox is checked. If no value is provided for the handler parameter, it will default to false.

See more about checkboxes in Razor forms here: https://www.learnrazorpages.com/razor-pages/forms/checkboxes

like image 193
Mike Brind Avatar answered Jun 10 '26 18:06

Mike Brind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!