CheckBoxList in ASP.Net MVC3 Razor

CheckBoxList in ASP.Net MVC3 Razor

 

If we want to create many check boxes or check boxes list we can call it inside a loop as follows.

1
2
3
4
@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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

1
@Html.CheckBoxList("SelectedUsers", AllUsersList, "Name", "ID")

To get the values of checked users we have two scenarios:
Strongly typed model scenario:
The model must have pro

perty with the same name that we provided to our helper method.

1
2
3
4
5
6
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.

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

1
2
3
4
5
6
[HttpPost]
public ActionResult ActionMethodName(FormCollection myForm)
{
String selectedusers = myForm["SelectedUsers"];
//Note this will return the selected users ids as comma separated string.
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s