Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

So say I am getting the data from data in format like name and value. These items will be return to the client in JSON format.

First we need to understand that there is no CheckBox list control is available in HTML. HTML has only CheckBox control. So let’s see that how a CheckBox list is rendered on the page. To check this, I took an asp.net CheckBox list control and assigned DataSource to a collection of Items. My ASPX page look like
FirstWhen we run it it is rendered as

checkboxlistserverNow lets see that how the html is generated for the above control

checkboxlisthtmlHere if we see then we find that CheckBox List is rendered as html table. Every item in CheckBox List is rendered as a tr element and in td element, there is two html control is created. one is CheckBox and another is Label. CheckBox shows the CheckBox on page and label shows the associated text.

Now we’ll render the same structure using jQuery Ajax. So I have created a server side WebMethod that returns CheckBox items in JSON format as

    [WebMethod()]
    public static string GetCheckBoxDetails()
    {
        List<CheckBoxItem> chkListAppointments = GetControlDetailsDB();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        return ser.Serialize(chkListAppointments);
    }

CheckBox Item is a class which has two properties name and value as

public class CheckBoxItem
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Now lets have a look on our aspx page

aspxforjquery

Here I have a button which calls a JavaScript method and this internally initiates ajax call and render the HTML for CheckBox List based on the data returned from the server. Lets have a look on JavaScript code

<script type="text/javascript" language="javascript">
        function PopulateCheckBoxList() {
            $.ajax({
                type: "POST",
                url: "CheckBoxList.aspx/GetCheckBoxDetails",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }
        function AjaxSucceeded(result) {
            BindCheckBoxList(result);
        }
        function AjaxFailed(result) {
            alert('Failed to load checkbox list');
        }
        function BindCheckBoxList(result) {

            var items = JSON.parse(result.d);
            CreateCheckBoxList(items);
        }
        function CreateCheckBoxList(checkboxlistItems) {
            var table = $('<table></table>');
            var counter = 0;
            $(checkboxlistItems).each(function () {
                table.append($('<tr></tr>').append($('<td></td>').append($('<input>').attr({
                    type: 'checkbox', name: 'chklistitem', value: this.Value, id: 'chklistitem' + counter
                })).append(
                $('<label>').attr({
                    for: 'chklistitem' + counter++
                }).text(this.Name))));
            });

            $('#dvCheckBoxListControl').append(table);
        }
    </script>

Here if we see the JavaScript method then we see first we initiate a Ajax call to the method GetCheckBoxDetails. When the Ajax call executes successfully then we parse the JSON and call CreateCheckBoxList method. In this method we create a table dynamically and loop through all the items and create a CheckBox and a label for every item. Finally append the table in the div dvCheckBoxListControl. Now let;s run and see the page

jquerycheckboxlistpag

When we click on Load button the JavaScript method fired and CheckBox List is created .Let’s see the generated HTML as

jquerycheckboxlistHere I have not included the whole HTML for the rendered CheckBox List control. If we see here then we find that we have created the similar HTML structure as created asp.net CheckBox List control as it is rendered as table and every item of CheckBoxList is rendered as a tr and it contains two control one CheckBox and other Label.

Hope you all have enjoyed the post and get benefited.

Cheers,
Brij

About these ads

6 thoughts on “Bind a CheckBox list from database using jQuery AJAX

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