1

I am using a model where a check box is there . where i am posting the form i always get more than one boolean value, Code is as follow

//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 am getting following value in str while debugging "true,false". Am i do anything wrong?

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
Dewasish Mitruka
  • 2,716
  • 1
  • 16
  • 20

2 Answers2

6

This is how Html.CheckBox was designed!

It always renders
<input name="test" type="checkbox" value="true" />
followed by a
<input name="test" type="hidden" value="false" />.
When you submit the form with the checkbox checked, you'll get test=true,false and when the checkbox is unchecked, you get test=false.

This is how it supports binding to a boolean value, because the ,false part is ignored. However, if you're binding to something else (such as string), that's when you'll see the "true,false" value.

If you want different behavior, you'll have to roll-your-own Html.CheckBoxAlt method. Here's a similar question, along with some code, that I wrote a while back: Passing checkbox selection through to an action

Community
  • 1
  • 1
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
2

MVC does things this way so it can tell the difference between "There is no checkbox called 'test'" and "The checkbox called 'test' is unchecked." Since HTML doesn't provide any built-in way to tell the difference, MVC makes it always send a "false" value, which will get overridden by a "true" value if you check the box.

The easiest solution is to make better use of MVC's approach. Rather than using the FormCollection, just use a parameter that the model binder can bind to:

public ActionResult HomeTest(bool test, HomeTest model)
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315