Pass checkbox selection into action

I have a set of flags that are used to indicate to the user which columns they want to see in the grid:

columnselector

Currently, each flag has its own key (which is essentially the name of the label) and is declared like this in my opinion:

@Html.CheckBox(column.Key, (Request.Form[column.Key] == null ? true : Request.Form[column.Key].Contains("true")), new { @class = "columnSelector" }) @Html.Label(column.HeaderText) 

The problem is that I need to get the values ​​from the collection of forms in my action, since otherwise I would have to have a bool parameter for each selector column. Alternatively, I thought I could name everything “columnselection” or something else, and then it will be passed to my action as an array of values, however then I lose the context of the value since I don't have the column key.

I do not want to create a viewmodel with a property for each checkbox, since this function is used on other screens with different columns, and I would like to keep it common.

Any thoughts on how I could achieve this column selection element in a clean and simple way?

+2
asp.net-mvc
Nov 11 2018-11-11T00:
source share
1 answer

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) { // selectedColumns will contain the keys of all the checked columns. } 

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); // Determine if this check should be selected: var state = html.ViewData.ModelState[name]; if (state != null) { var values = (string[])state.Value.ConvertTo(typeof(string[])); selected = Array.IndexOf(values, value) != -1; } if (selected) tag.MergeAttribute("checked", "checked"); return new HtmlString(tag.ToString(TagRenderMode.SelfClosing)); } 
+1
Nov 11 '11 at 6:01
source share



All Articles