CheckBox

Last post 10-14-2008 9:44 PM by levib. 3 replies.

Sort Posts:

  • CheckBox

    10-14-2008, 9:10 PM
    • Contributor
      3,569 point Contributor
    • shapper
    • Member since 11-28-2004, 9:15 PM
    • Posts 2,947

    Hello,

    I am rendering some checkboxes on my view as follows:

              <ul>
              <% foreach (Role role in ViewData.Get<AccountBook>("Account").Roles) { %>
                <li>
                  <%= role.Description %>
                  <%= Html.CheckBox("Roles", false, new { value = role.Type })%>
                </li>           
              <% } %>
              </ul>   

    When I update my model to get the values how should be the variable or the object to get the checkboxes that were selected? How can I do this?

    Thanks,

    Miguel

  • Re: CheckBox

    10-14-2008, 9:28 PM
    • Contributor
      4,499 point Contributor
    • levib
    • Member since 07-23-2007, 7:50 PM
    • Redmond, WA
    • Posts 782

    The Html.CheckBox() helper is not meant to be used in a loop.  For this, write the <input ... /> tags manually.  Your action method will receive a string array containing the checked values.

    For example, if you had:
    <input type="checkbox" name="theBox" value="foo" />
    <input type="checkbox" name="theBox" value="bar" />
    <input type="checkbox" name="theBox" value="baz" />

    Then your action result would look like:
    public ActionResult SomeMethod(string[] theBox) {
      // if only 'foo' and 'baz' are checked, theBox will be a two-element
      // array containing the values 'foo' and 'baz'.
    }

  • Re: CheckBox

    10-14-2008, 9:35 PM
    • Contributor
      3,569 point Contributor
    • shapper
    • Member since 11-28-2004, 9:15 PM
    • Posts 2,947

    levib:

    Then your action result would look like:

    public ActionResult SomeMethod(string[] theBox) {
      // if only 'foo' and 'baz' are checked, theBox will be a two-element
      // array containing the values 'foo' and 'baz'.
    }

     

    Got it!

    levib:

    The Html.CheckBox() helper is not meant to be used in a loop.  For this, write the <input ... /> tags manually.

     

    Why? Is it a question of performance?

  • Re: CheckBox

    10-14-2008, 9:44 PM
    • Contributor
      4,499 point Contributor
    • levib
    • Member since 07-23-2007, 7:50 PM
    • Redmond, WA
    • Posts 782

    shapper:
    Why? Is it a question of performance?

    It's not a performance issue.  If you look at the HTML generated by the Html.CheckBox() helper, you'll note that it renders a hidden input with the same name as the checkbox input element.  If you generate multiple checkboxes on your page where each checkbox has the same name (as in the loop you wrote above), these hidden inputs will interfere with those values.

Page 1 of 1 (4 items)