Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is checkbox always true

Tags:

asp.net-mvc

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);
like image 672
Daveo Avatar asked Nov 13 '22 10:11

Daveo


1 Answers

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.

like image 195
twilson Avatar answered Dec 18 '22 09:12

twilson