HTML.CheckBox Behavior

I am using a model where there is a checkbox. where I submit the form, I always get more than one boolean, the code is as follows

//controller code // GET: /Home/ // GET: /Home/Test public ActionResult HomeTest() { HomeTest ht = new HomeTest(); return View(ht); } [AcceptVerbs(HttpVerbs.Post)] [ValidateInput(false)] public ActionResult HomeTest(FormCollection collection, HomeTest model) { string str = collection["test"].ToString(); return View(model); } //View Html <%= Html.CheckBox("test") %> 

I get the following value in str when debugging "true, false". Am I something wrong?

+1
asp.net-mvc
Dec 08 '11 at 20:24
source share
2 answers

This is how Html.CheckBox was designed!

It always assists <input name="test" type="checkbox" value="true" />
then followed by <input name="test" type="hidden" value="false" /> .
When you submit the form with the checkbox selected, you will receive test=true,false , and if the checkbox is not selected, you will receive test=false .

This is how it maintains binding to the boolean value, because the ,false part ,false ignored. However, if you are attached to something else (for example, string ), it means that you will see the value "true,false" .

If you need other behavior, you will have to use your own Html.CheckBoxAlt method. Here's a similar question, along with some code that I wrote some time ago: Passing a checkbox selection into action

+6
Dec 08 '11 at 20:29
source share

MVC does this in such a way that it can distinguish between โ€œThere is no flag calledโ€œ test โ€andโ€œ the flag โ€œtestโ€ is not set. Since HTML does not provide a built-in demarcation method, MVC always sends a false value that will be overridden. โ€ true "value if you check the box.

The simplest solution is to better use the MVC approach. Instead of using FormCollection, just use a parameter that the model binding can bind to:

 public ActionResult HomeTest(bool test, HomeTest model) 
+2
Dec 08 '11 at 20:29
source share



All Articles