Just add value="true" to the input tag. And use a hidden with value="false" as shown below.
Here Data Source is Server Name and Initial Catalog is database Name. Now open home controller and write following code in it. Add the namespace using BindCheckBoxUsingMVC. Models on the top.As this namespace contains DbAccess and Sports Class.
@Html.EditorFor(x => x.Remember)
Will generate:
<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />
How does it work:
checkbox
remains unchecked, the form submits only the hidden
value (false)true
for the model's bool
property<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
This will always send the default value, if checked.
Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.
So the value for Remember is false, and sets the value on the checkbox element to false. This means that when you then select the checkbox, you are posting the value "false" with the form. When you don't select it, it doesn't get posted, so the model defaults to false. Which is why you are seeing a false value in both cases.
The value is only passed when you check the select box. To do a checkbox in Mvc use
@Html.CheckBoxFor(x => x.Remember)
or if you don't want to bind the model to the view.
@Html.CheckBox("Remember")
Mvc does some magic with a hidden field to persist values when they are not selected.
Edit, if you really have an aversion to doing that and want to generate the element yourself, you could do.
<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked=\"checked\"" : "") />
Use only this
$("input[type=checkbox]").change(function () {
if ($(this).prop("checked")) {
$(this).val(true);
} else {
$(this).val(false);
}
});
Instead of
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
use:
@Html.EditorFor(x => x.Remember)
That will give you a checkbox specifically for Remember
Okay, the checkbox is a little bit weird. When you use Html helper, it generates two checkbox inputs on the markup, and both of them get passed in as a name-value pair of IEnumerable if it is checked.
If it is not checked on the markup, it gets passed in only the hidden input which has value of false.
So for example on the markup you have:
@Html.CheckBox("Chbxs")
And in the controller action (make sure the name matches the checkbox param name on the controller):
public ActionResult Index(string param1, string param2,
string param3, IEnumerable<bool> Chbxs)
Then in the controller you can do some stuff like:
if (Chbxs != null && Chbxs.Count() == 2)
{
checkBoxOnMarkup = true;
}
else
{
checkBoxOnMarkup = false;
}
I know this is not an elegant solution. Hope someone here can give some pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With