The Html.CheckBox method has a weird implementation. Flags will have a unique name value and, in essence, a true/false value. This means that the value will be easily mapped to the bool parameter in Action.
As you obviously noticed, this creates a difficult situation when your checkboxes are dynamic.
The solution is to create your own flags using a common name and having a unique value s. They will be displayed very well in your action!
See also this question for some great examples and explanations .
Here's the desired action:
public ActionResult SetSelectedColumns(string[] selectedColumns) {
Here’s how to display the HTML correctly:
<input type="checkbox" name="selectedColumns" value="@column.Key" @(column.Selected ? "checked='checked'" : "") />
I highly recommend including this functionality in the extension method so that you can also include ModelState and htmlAttributes . Here is my unverified attempt:
public static HtmlString CheckBoxAlt(this HtmlHelper html, string name, string value, bool selected, object htmlAttributes) { var tag = new TagBuilder("input"); if (htmlAttributes != null) tag.MergeAttributes(new RouteValueDictionary(htmlAttributes)); tag.MergeAttribute("type", "checkbox"); tag.MergeAttribute("name", name); tag.MergeAttribute("value", value);
Scott Rippey Nov 11 '11 at 6:01 2011-11-11 06:01
source share