How to submit unchecked checkbox also
This is a common issue with checkboxes in HTML forms and isn't unique to ASP.NET.
The answer is to have a hidden field that accompanies each checkbox. When the checkbox is modified, use a client-side event to update the hidden field.
The hidden field will always be submitted.
However, since you're using ASP.NET MVC, if you use the HTML.CheckBoxFor
helper, it will handle this for you automatically.
This is a very common problem - when checkbox isn't selected it wont send to server value off/ false by itself. Most popular answer that I found was to add hidden field with the same name as checkbox and value = false. But then when someone checked it it sent me two values.
And I didn't like it. This is what I did:
Somewhere in HTML:
<input type="checkbox" name="${name}" onclick="true" >
In JQuery:
First step is to set hidden values on all checkboxes that aren't checked.
$(document).ready(function () {
$(".checkbox").each(function () {
if ($(this).prop("checked") == undefined) {
$(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value="off">")
}
}
)
});
Secondly we have to react on user clicking the check-box: while unselecting add hidden field, when selecting - remove next sibling in DOM - we expected hidden field there.
WARNING: when check-boxes have common parent you should check if next sibling's type is hidden and then remove it!:
$(".checkbox").click(function () {
if ($(this).prop("checked") == undefined) {
$(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value=off>")
} else {
$(this).next().remove();
}
}
);
And it works for me :)