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

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

    • Hi,

      Thanks for your question.

      I did not include the details getting the data from data as the focus point was how to bind that we got from the database. You can see that GetControlDetailsDB method returns List and CheckBoxItem has just two properties name and value as discussed in the post. These two values from each item in checkbox, are getting populated from database in the method you asked. Hope it clears.

    • You cannot access this control on server, because it is nor server side control, we just created the HTML based on the data received from server via jQuery AJAX. Now if you want to send the selection to server, you can read that information via jQuery and send it via ajax request.

      • I am really stack with this, I’m using this example but just receiving an error alert. I have a list from database following the same steps, nothing but none. If you could help, I´d really appreciate…
        This is my E-mail: safeetyy@gmail.com

      • Are you using webmethod? First check whether you are getting the checkbox items and able to serialize at server. Then check whether you are able to get at client side via Ajax call? Share the error details

      • Yes Sir I am using Webmethod:

        [WebMethod]
        public static string _Bind()
        {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Entities dbn = new Entities();

        var viewModel = new List();

        try
        {

        var TodosEstudantes = dbn.tEstudantesTurmas.Include(x => x.Estudante);

        foreach (var estudante in TodosEstudantes)
        {
        viewModel.Add(new EstudanteSeleccionado
        {
        ID = estudante.Id,
        Nomes = estudante.Estudante.Nomes,
        Seleccionado = Convert.ToBoolean(estudante.Id)
        });
        }

        return ser.Serialize(viewModel);
        }
        catch (Exception exe)
        {

        return ser.Serialize(exe.Message.ToString());
        }

        }

        The error message is on
        function AjaxFailed(result) {
        alert(‘Failed to load checkbox list’);
        }

        Setting a BreakPoint int the begining the program does not stop. Only if I change the method to JsonResult it stops but does not return the checkboxList values.

      • As you are using MVC, prefer using Action method. Make sure you are allowing HTTPGet from server, and initiating GET call from client side

Leave a comment