Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining which items are selected in CheckBoxList using Request.Form

Using the approach shown in the question here, I am able to get the selected items values from my CheckBoxList:

var selectedCheckBoxItems = from key in Request.Form.AllKeys
                        where key.Contains(cbl.ID)
                        select Request.Form.Get(key);

I can then iterate over the results:

foreach (var item in selectedCheckBoxItems)
{

}

The problem is that item is just the posted value, which for a checkbox, is simply the string "on".

on

I need to be able to determine which item is "on", either by index or some other method.

Question: How do I determine which items in the CheckBoxList are selected, using Request.Form ?

Here is my CheckBoxList definition:

<asp:CheckBoxList runat="server" ID="cblAnimalType" SelectionMode="Multiple" DataTextField="OptionText" DataValueField="OptionId"  AutoPostBack="True"/>

Items are added to the list from code behind:

DataTable dt = GetData(SqlGetListOptions, paramList);
cbl.DataSource = dt;
cbl.DataBind();

The other important thing to know is that ViewStateMode="Disabled", so I must use Request.Form to get the selected items.


In response to a comment, here is how the HTML for the CheckBoxList renders:

html


@Leopard pointed out that he sees values rendered in the HTML which is not occurring in my situation. AdamE's answer to this question explains why. I have the following line in web.config:

<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">

which explains why I see "on" instead of the actual value of the selected items. I am not able to just yank the compatibility out of web.config without verifying it won't break something else, but it appears that if that setting is safe to remove, the checkbox list values will be accessible from codebehind.

like image 863
devlin carnate Avatar asked Jun 07 '16 22:06

devlin carnate


3 Answers

As you are binding the checkboxList from Database with OptionId feild you can check which checkboxes are selected and store their value in List<int> assuming their value is int.

Then again when you populate the checkboxlist you can check which value is present in the list stored earlier and based on value you can select the relevant checkbox.

Here is a sample code

List<int> SelectedCheckBoxes = new List<int>();
var selectedCheckBoxItems = from key in Request.Form.AllKeys
                                    where key.Contains(cblAnimalType.ID)
                                    select Request.Form.Get(key);
foreach (var item in selectedCheckBoxItems)
{
  SelectedCheckBoxes.Add(int.Parse(item.ToString()));
}

Then again when you populate the checkboxlist you can find the items by value and select them

foreach (ListItem listItem in cblAnimalType.Items)
{
  if (SelectedCheckBoxes.Contains((int.Parse(listItem.Value))))
   {
     listItem.Selected = true;
   }
}

You may need to store the SelectedCheckBoxes List in session depending on how you are populating the checkboxlist.

Update

As per discussion with you you were using Asp.net 4.0 but your checkboxes didn't have a value attribute which should have been there.

This is happening because you are using controlRenderingCompatibilityVersion="3.5" which is no longer needed as you are already using Asp.Net 4.0.

So removing this line from web.congif will solve the issue and you will be able to get the value of checkbox instead of just getting on

<pages controlRenderingCompatibilityVersion="3.5" />
like image 80
Mairaj Ahmad Avatar answered Nov 07 '22 04:11

Mairaj Ahmad


I thought of one way to do it, by adding the key to the results. I'm not entirely happy with this method due to the string parsing that's required to get the index. Perhaps someone else has a better method?

The general idea is to add the key to the results:

var selectedCheckBoxItems = from key in Request.Form.AllKeys
                        where key.Contains(cbl.ID)
                        select new {Value = Request.Form.Get(key), Key = key};
foreach (var item in selectedCheckBoxItems)
{
   var val = item.Value;
   var key = item.Key;
}

I can then parse the key to find the index, which is what I need in order to set the selected option(s):

var selectedCheckBoxItems = from key in Request.Form.AllKeys
                        where key.Contains(cbl.ID)
                        select new {Value = Request.Form.Get(key), Key = key};

string[] stringParse = new string[] {listName.Replace(" ", "") + '$'};

foreach (var item in selectedCheckBoxItems)
{
    var val = item.Value;
    var key = item.Key;
    var idxArray = key.Split(stringParse, StringSplitOptions.None);
    var idxString = idxArray[idxArray.Length - 1];
    int idxInt;
    if (Int32.TryParse(idxString, out idxInt))
    {
        cbl.Items[idxInt].Selected = true;
    }
}
like image 29
devlin carnate Avatar answered Nov 07 '22 03:11

devlin carnate


Here is another way to parse the key to get the selected indexes. It also uses the UniqueID property to find the relevant keys.

var selectedCheckBoxItems = from key in Request.Form.AllKeys
                            where key.Contains(cblAnimalType.UniqueID)
                            select new { Value = Request.Form.Get(key), Key = key };

foreach (var item in selectedCheckBoxItems)
{
    var val = item.Value;
    string indexToken = item.Key.Replace(cblAnimalType.UniqueID, "");
    int index = int.Parse(Regex.Replace(indexToken, @"[^\d]", ""));
    ...
}
like image 1
ConnorsFan Avatar answered Nov 07 '22 05:11

ConnorsFan