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

How To Get CheckBox Selected Values in Controller In MVC3


Introduction

In this article i am going to define u you how we can get selected values of checkbox in mvc3 in controller.in this article u will also get to know about multiple form in a single view how to use them.

Step 1: Make a new Empty Project using mvc3 in visual studio 2010.

Step 2: Now Add Collection Class in Model folder by Right click on model whose code would be such as below given.

 public class MyViewModel
    {
        public int Id { get; set; }
        public bool Checkbox { get; set; }
        public string Value { get; set; }
    }
 
 
    // view model for checklistbox
    public class CheckBoxListViewModel
    {
        public List<CheckListBoxItem> Items { get; set; }
 
        // the name of this list should be the same as of the CheckBoxes otherwise you will not get any result after post
        public List<string> SelectedValues { get; set; }
    }
 
    // represents single check box item
    public class CheckListBoxItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
        public bool IsCheck { get; set; }
    }

Step 3: After this add a HomeController in Controller Folder and write in that below given code.

public ActionResult Index()
        { 
 
            var list = new List<MyViewModel>
            {
                new MyViewModel { Id = 1, Checkbox = false ,Value="Coal"},
                new MyViewModel { Id = 2, Checkbox= false ,Value="Cotton"},
                new MyViewModel { Id = 3, Checkbox = false ,Value = "Fabric"},
            };
            var outObj = list.Select(row => new SelectListItem()
                            {
                                Text = row.Value,
                                Value = row.Id.ToString(CultureInfo.InvariantCulture),
                                Selected = row.Checkbox
                            });
            ViewBag.keydata = outObj;
            // pass ViewModel object to View for display
 
            return View();
        }

Step 4 :  Now Add your view index.cshtml in view folder and paste in his below given code.

@{
    ViewBag.Title = "Index";
    var obj = ViewBag.keydata;
}
@using (Html.BeginForm("Index", "Home"))
{
    IEnumerable<SelectListItem> ct = ViewBag.keydata;
    foreach (var item in ct)
    {
    @Html.CheckBox("chk", item.Selected, new { value = item.Value });<label>@item.Text</label>
    }
<div>
       <input type="submit" value="Send" name="action:Send" /></div>
}

Step 5:  Now Make your Index Action with HttpPost Attribute in Controller which is below given.

 [HttpPost]
        [MultipleButton(Name = "action", Argument = "Send")]
        public ActionResult Index(FormCollection obj)
        {
           
            if (obj != null)
            {
                string[] AllStrings = obj["chk"].Split(',');
                foreach (string item in AllStrings)
                {
                    if (item.Contains("false"))
                    {
 
                    }
                    else
                    {
                        var outk = item;
                    }
 
 
 
                    // handle value
                }
            }
           
            return RedirectToAction("Index", "Home");
        }
Now Run by pressing f5 and See by putting Result in Your action you will get your all selected
Check boxes values.

If you Want to Download complete source of this article you can get to download it by click on below given url

https://docs.google.com/file/d/0B-sDsBkcsM1YWV9PWVUwYlVHRjA/edit?usp=sharing