Breaking News

Wednesday, March 16, 2011

How to get checked values out of a CheckBoxList?

Have you ever thought of why exactly do you love custom extensions? Roll out one just for this case:

public static class ControlExtensions
{
    public static string GetCheckedValues(this CheckBoxList list)
    {
        return String.Join(",", list.Items.OfType()
                                             .Where(s => s.Selected)
                                             .Select(s => s.Value).ToArray());
    }

}



Usage example, somewhere in ASP.NET MVC:

public ActionResult Index()
{
    CheckBoxList lst = new CheckBoxList();
    lst.Items.Add(new ListItem("one", "1"));
    lst.Items.Add(new ListItem("two", "2"));
    lst.Items.Add(new ListItem("three", "3"));
    lst.Items.Add(new ListItem("four", "4"));

    lst.Items[0].Selected = true;
    lst.Items[1].Selected = true;

    ViewData["Message"] = lst.GetCheckedValues();// Here.

    return View();
}

Enjoy!

No comments:

Post a Comment

Designed By Published.. Blogger Templates