Generic CheckBoxList in ASP.Net MVC

In ASP.Net web forms you can easily create a list of check boxes and bind it into a data collection using CheckBoxList control and specify which property will be the text of each check box and which one will be the value of the check box. You even don't need to write it, you can drag it from tools window, drop it into your page and set its properties and style with wizards that Visual studio provide.

But in ASP.Net MVC there is no any server controls like that exists in web forms, all what we have is a helper methods to create HTML tags. In ASP.Net MVC we have two helpers methods for creating a check box, Html.CheckBox and Html.CheckBoxFor that will be rendered as just one check box. If we want to create many check boxes or check boxes list we can call it inside a loop as follows
@foreach (var item in MyCollection)
{
   @Html.CheckBox("checkBoxName", new {value=item.checkBoxValue })@item.CheckBoxText<br />
}
Here is a generic extension method for create a check boxes list in an elegant manner.
public static MvcHtmlString CheckBoxList<T>(this HtmlHelper helper,
                                               String name,
                                               IEnumerable<T> items,
                                               String textField,
                                               String valueField,
                                               IEnumerable<T> selectedItems=null)
{
  Type itemstype = typeof(T);
  PropertyInfo textfieldInfo = itemstype.GetProperty(textField,typeof(String));
  PropertyInfo valuefieldInfo = itemstype.GetProperty(valueField);

  TagBuilder tag;
  StringBuilder checklist = new StringBuilder();
  foreach(var item in items)
  {
      tag = new TagBuilder("input");
      tag.Attributes["type"] = "checkbox";
      tag.Attributes["value"] = valuefieldInfo.GetValue(item,null).ToString();
      tag.Attributes["name"] = name;
      if (selectedItems != null && selectedItems.Contains(item))
      {
          tag.Attributes["checked"] = "checked";
      }
      tag.InnerHtml = textfieldInfo.GetValue(item,null).ToString();
      checklist.Append(tag.ToString());
      checklist.Append("<br />");
  }
  return MvcHtmlString.Create(checklist.ToString());
}
In the first three lines we get the type of the data collection then get the property info of text field and value field that will be used to create each check box. We enumerate over the input data collection and use TagBuilder class to create input tag and set its attributes like type,name, and value. We check the selectedItems collection to set checked attribute of our check box.
Say we have a list of users that we display it as checkboxlist to select some users, we can use our helper method as follows
@Html.CheckBoxList("SelectedUsers", AllUsersList, "Name", "ID")
To get the values of checked users we have two scenarios:
  1. Strongly typed model scenario:
    The model must have property with the same name that we provided to our helper method.
    class MyModel
    {
       //Note you can define it as array of strings, dates or any primitive data type 
       //according to the type of the property of value field.
       Public Int32[] SelectedUsers{get; set;}
    }
    when we post the view, the model binder will bind the values of selected check boxes into the property with the same name.
  2. Not Strongly typed model scenario:
    In this case, our action method that will handle our request(decorated by HttpPost attribute) should be defined to accept a FormCollection parameter that will contain key with the same name we provided to our helper method
    [HttpPost]
    public ActionResult ActionMethodName(FormCollection myForm)
    {
      String selectedusers = myForm["SelectedUsers"];
      //Note this will return the selected users ids as comma separated string.
    }
    
You can download sample code here

Comments

  1. Hi, this is an amasing work, but ive one question ( im pretty new at MVC ) i was wondering i wich moment the helper saves the selected items, because im not been able to see it, thanks!

    ReplyDelete
    Replies
    1. I mentioned it in the last section. you can read the values of selected checkboxes by two ways according to your view if it is Strongly typed view or not.

      you can download sample code from http://db.tt/Seyhu3Mm
      in the controller class you will find two methods for post action one of them is commented. One for strongly typed view and one for reading the values of checkboxes from posted data (FormCollection object).

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I can't say enough thanks to you!!! you just save my day!!! It works! it works! many many thanks!!

    ReplyDelete

Post a Comment

Popular posts from this blog

Android : How to change progress bar color at runtime programmatically?

ASP.Net MVC : Conditional Validation using ValidationAttribute

How to fire RowCommand event of nested GridView?