I am using @Html.CheckBoxFor(x => x.Luxury)
which generates the following HTML
<input id="Luxury" type="checkbox" value="true" name="Luxury" data-val-required="The Luxury field is required." data-val="true">
<input type="hidden" value="true" name="Luxury">
So no matter what I set the check box to the controllers action is getting the value as TRUE, even when not checked.
How do I get MVC not to make a checkbox return true. When I debug on the first Brace even before I call any code I can see Banner.Luxury is always = true
My Class
public class Banner
{
public int Id { get; set; }
public bool Luxury { get; set; }
}
[HttpPost]
public ActionResult Save(Banner banner)
....
}
Looking at this question Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name? does not help as when I run
Convert.ToBoolean(Request.Form.GetValues("Luxury"));
There is only "true" not "true;false";
This workaround works but its a bad HACK
@{ if (Model.Luxury)
{
<input type="checkbox" name="Luxury" value="1" checked="checked" />
}
else
{
<input type="checkbox" name="Luxury" value="1" />
}
}
code
banner.Luxury = !(Request.Form.GetValues("Luxury") == null);
Change it to:
<input type="hidden" value="false" name="Luxury">
<input id="Luxury" type="checkbox" value="true" name="Luxury" data-val-required="The Luxury field is required." data-val="true">
That way when you chek the checkbox it will become true, otherwise it will be false. The order of controls matters.
In your example even if you changed the order, you were always returning true.
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