Blog

Tagged by 'checkboxlist'

  • The thing that annoys me when using ASP.NET controls is the amount of cluttered HTML that gets generated. It sometimes reminds of my early web development days when Dreamweaver was the development tool of choice. That was a long time ago!

    CheckBoxList

    By default when using a Checkbox or Radio button list, the following markup is generated:

    <table id="MainContent_TestCheckList">
        <tbody>
                <tr>
                    <td>
                        <input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label>
                    </td>
                    <td>
                        <input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label>
                    </td>
                    <td>
                        <input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label>
                    </td>
                    <td>
                        <input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label>
                    </td>
                </tr>
        </tbody>
    </table>
    

    Yuck!

    Thankfully, this control contains a property called “RepeatLayout” that gives us the option to render our list of checkboxes or radio buttons in a much nicer way.

    Flow

    Rendered within a <span> container.

    <span id="MainContent_TestCheckList">
        <input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label>
        <input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label>
        <input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label>
        <input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label>
    </span>
    

    OrderedList or UnorderedList

    Rendered within a <ul> (unordered list) or <ol> (ordered list). Note: Multi-column layouts (RepeatColumns attribute) are not supported when using this option.

    <ul id="MainContent_TestCheckList">
        <li><input type="checkbox" value="1" name="ctl00$MainContent$TestCheckList$0" id="MainContent_TestCheckList_0"><label for="MainContent_TestCheckList_0">Item 1</label></li>
        <li><input type="checkbox" value="2" name="ctl00$MainContent$TestCheckList$1" id="MainContent_TestCheckList_1"><label for="MainContent_TestCheckList_1">Item 2</label></li>
        <li><input type="checkbox" value="3" name="ctl00$MainContent$TestCheckList$2" id="MainContent_TestCheckList_2"><label for="MainContent_TestCheckList_2">Item 3</label></li>
        <li><input type="checkbox" value="4" name="ctl00$MainContent$TestCheckList$3" id="MainContent_TestCheckList_3"><label for="MainContent_TestCheckList_3">Item 4</label></li>
    </ul>
    

    Table

    We won’t be using this option.

  • To be able to retrieve values from a ASP.NET CheckBoxList control or a group of HTML checkboxes, use the following jQuery:

    $(document).ready(function () {
        var checkboxValues = [];
    
        $('#<%=MyCheckBoxList.ClientID %> input[type=checkbox]').click(function () {
            $('input[type=checkbox]:checked').each(function () {
                checkboxValues.push(this.value);
            });        
        });
        
        var values = checkboxValues.toString(); //Output Format: 1,2,3
    });
    

    If you do use this code snippet on a CheckBoxList, take a look that this article on how to create a custom CheckBoxList control with a value attribute.

  • ASP.NET server controls is a great way to quickly build a page with dynamic functionality. Even though we do not have much of direct control over the way these controls are rendered, they do a pretty good job and its not very often I get annoyed with them.

    Until now.

    Generally, I find myself using the .Attributes.Add() method when needing to add additional attributes to certain server controls. No problem! In this case, I wanted to add a “value” attribute that will contain the record ID for that checkbox. I can then use this value within my JavaScript. I would have thought a value attribute would already be there. Its perfectly valid HTML mark-up:

    <form>
        <input type="checkbox" name="vehicle" value="Volvo" />
        <input type="checkbox" name="vehicle" value="Volkswagen" />
    </form> 
    

    For some reason, when I tried to add my custom attributes after my CheckBoxList was databound (as shown below), the attribute was simply ignored.

    NewsCheckList.Items[0].Attributes["value"] = "1";
    NewsCheckList.Items[1].Attributes["value"] = "2";
    NewsCheckList.Items[2].Attributes["value"] = "3";
    

    So I decided the best way forward would be to create a custom CheckBoxList control that would contain a value attribute. I based my code from an old (but very useful) article that can be found here.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Web.UI;
    using System.Collections;
    using System.ComponentModel;
    
    namespace Site.WebControls
    {
        [DefaultProperty("Text"),
        ToolboxData("<{0}:CheckBoxValueList runat=server></{0}:CheckBoxValueList>")]
        public class CheckBoxValueList : CheckBoxList
        {
            protected override void Render(HtmlTextWriter writer)
            {
                StringBuilder sb = new StringBuilder();
                TextWriter tw = new StringWriter(sb);
                
                HtmlTextWriter originalStream = new HtmlTextWriter(tw);
                base.Render(originalStream);
                string renderedText = sb.ToString();
    
                int start = 0;
                int labelStart = 0;
                int end = renderedText.Length;
    
                for (int i = 0; i < this.Items.Count; i++)
                {
                    StringBuilder itemAttributeBuilder = new StringBuilder();
    
                    end = renderedText.Length;
                    start = renderedText.IndexOf("<input", start, end - start);
                    labelStart = renderedText.IndexOf("<label", start, end - start);
    
                    this.Items[i].Attributes.Render(new HtmlTextWriter(new StringWriter(itemAttributeBuilder)));
    
                    renderedText = renderedText.Insert(labelStart + 7, itemAttributeBuilder.ToString() + " ");
                    renderedText = renderedText.Insert(start + 7, String.Format("{0} value=\"{1}\" ", itemAttributeBuilder.ToString(), this.Items[i].Value));
                    start = renderedText.IndexOf("/>", start, renderedText.Length - start);
                }
                
                writer.Write(renderedText);
            }
        }
    }