Monday, August 24, 2009

ASP.NET MVC - Html.CheckBox() generates two HTML tags

Let's say that you have this code in your view:
<%= Html.CheckBox("Active") %>
That will generate following HTML code:
<input id="Active" name="Active" type="checkbox" value="true" />
<input name="Active" type="hidden" value="false" />
Why two inputs with same name? Well, if checkbox is left unchecked by user it will not be submitted in POST request and in such case ASP.NET uses hidden field for proper data binding.

So how can you get checkbox state in your controller?
public ActionResult ReadCB(FormCollection form)
    bool active = false;
    if (form["Active"].Contains("true))
        active = true;
    // ...
    return View();

No comments:

Post a Comment