HTML.CheckBox行为

Dew*_*uka 1 asp.net-mvc

我正在使用一个模型,其中有一个复选框.我在哪里发布表单我总是得到多个布尔值,代码如下

//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") %>
Run Code Online (Sandbox Code Playgroud)

在调试"true,false"时,我在str中获得了以下值.我做错了吗?

Sco*_*pey 6

这是怎么Html.CheckBox设计的!

它总是渲染
<input name="test" type="checkbox" value="true" />
后跟一个
<input name="test" type="hidden" value="false" />.
当您选中复选框提交表单时,您将获得test=true,false,当取消选中该复选框时,您将获得test=false.

这是它支持绑定到boolean值的方式,因为该,false部分被忽略.但是,如果你绑定了其他东西(例如string),那就是你会看到"true,false"价值的时候.

如果您想要不同的行为,则必须使用自己的Html.CheckBoxAlt方法.这是一个类似的问题,以及一些代码,我写了一段时间:将复选框选择传递给一个动作