Populate an ASP.NET ListBox from JSON results using jQuery

Posted by: Suprotim Agarwal , on 1/27/2010, in Category jQuery and ASP.NET
Views: 118402
Abstract: This article demonstrates how to populate an ASP.NET ListBox using data coming from a JSON Serialized ASP.NET Web Service.
Populate an ASP.NET ListBox from JSON results using jQuery
 
This article demonstrates how to populate an ASP.NET ListBox using data coming from a JSON Serialized ASP.NET Web Service. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter has been modified to publish it as an article.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how to populate an ASP.NET ListBox from data coming from a JSON Serialized ASP.NET Web Service
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Populate a ListBox from JSON Results</title>
    <script language="javascript" type="text/javascript"
    src="http://code.jquery.com/jquery-latest.js"></script>
   
    <script type="text/javascript">
        $(function() {
            var firstParam = 'F';
            var radBtn = $("table.tbl input:radio");
            var lBox = $('select[id$=lb]');
            $(radBtn).click(function() {
                lBox.empty();
                var firstParam = $(':radio:checked').val();
                $.ajax({
                    type: "POST",
                    url: "Services/EmployeeList.asmx/FetchEmpOnGender",
                    data: "{empSex:\"" + firstParam + "\"}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        var gender = msg.d;
                        if (gender.length > 0) {
                            var listItems = [];
                            for (var key in gender) {
                                listItems.push('<option value="' +
                                key + '">' + gender[key].FName
                                + '</option>');
                            }
                            $(lBox).append(listItems.join(''));
                        }
                        else {
                            alert("No records found");
                        }
                    },
                   error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            });
        });
    </script>
 
     
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Click on a Radio Button to retrieve 'Gender' based data</h2>
        <br /><br />
        <asp:RadioButtonList ID="rbl" runat="server" class="tbl"
        ToolTip="Click on this RadioButton to retrieve data">   
            <asp:ListItem Text="Male" Value="M"></asp:ListItem>   
            <asp:ListItem Text="Female" Value="F"></asp:ListItem>            
        </asp:RadioButtonList><br />
        <asp:ListBox ID="lb" runat="server"></asp:ListBox>
    </div>
    </form>
</body>
</html>
In this example, we will see how to consume an ASP.NET Web Service (EmployeeList.asmx) that is JSON Serialized. The data source for this web service is List<Employees> in the Employee.cs class. The class can be downloaded from the source code available with this article. Here’s a snapshot of what the class looks like
SnapshotofClass
If you look at the EmployeeList.cs file, you will observe that the method has been decorated with the [WebMethod] attribute to allow calls from client script
C#
[WebMethod]
    public List<Employee> FetchEmpOnGender(char empSex)
    {
        var emp = new Employee();
        var fetchEmp = emp.GetEmployeeList()
            .Where(m => m.Sex == empSex);
        return fetchEmp.ToList();
    }
VB.NET
<WebMethod> _
Public Function FetchEmpOnGender(ByVal empSex As Char) As List(Of Employee)
            Dim emp = New Employee()
            Dim fetchEmp = emp.GetEmployeeList().Where(Function(m) m.Sex = empSex)
            Return fetchEmp.ToList()
End Function
 
The FetchEmpOnGender() method calls the GetEmployeeList() method on the Employee class which returns a List<Employee>. The UI contains two radio buttons ‘Male’ and ‘Female’ which when selected, passes in the gender information to the web service. Depending on the input received, the web service method filters and returns data for the gender requested.
Note: If a method is not marked with [ScriptMethod] attribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON.
To consume this web service using jQuery $.ajax(), two important points to note is that the request should be a POST request and the request’s content-type must be ‘application/json; charset=utf-8’. The code structure looks similar to the following:
$.ajax({
    type: "POST",
    url: "Services/EmployeeList.asmx/FetchEmpOnGender",
    data: "{empSex:\"" + firstParam + "\"}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
 
Also observe the way we are passing in the gender parameter using a ‘special formatting’ in the $.ajax() call
data: "{empSex:\"" + firstParam + "\"}"
Once we receive the results, we loop through it and populate an array ‘listItems’ with the FirstName values by passing in a key to the FName value (gender[key].FName))
success: function(msg) {
    var gender = msg.d;
    if (gender.length > 0) {
        var listItems = [];
        for (var key in gender) {
            listItems.push('<option value="' +
            key + '">' + gender[key].FName
            + '</option>');
        }
    
The final step is to populate the ListBox using the populated array
$(lBox).append(listItems.join(''));
When you run the application, click on the radio button, to retrieve the FirstName of Employees. Clicking on the ‘Male’ radio button fetches the following results:
Male
Whereas clicking on the ‘Female’ radio button fetches the following results:
Female
See a Live Demo
I hope you found this article useful and I thank you for viewing it. This article was taken from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which contains similar recipes that you can use in your applications. The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Ben on Friday, January 29, 2010 4:33 PM
I have been trying to replicate this all day and it keeps giving my XML and not JSON.  It is also throwing a parser error.  It is driving me nuts.
Comment posted by Suprotim Agarwal on Friday, January 29, 2010 9:56 PM
Ben: Make sure your method is not marked with [ScriptMethod] attribute. I just tried the example again and here's a screenshot with the results in JSON format

http://i849.photobucket.com/albums/ab56/a2zknowledge/jQuery/JsonResults.jpg
Comment posted by Miklos on Tuesday, May 4, 2010 3:12 AM
The approach itself is nice. But when running the demo, the control flickers. Try to make it smoother.
Comment posted by john balconi on Tuesday, May 4, 2010 10:33 AM
Check this
http://www.c-sharpcorner.com/UploadFile/sridhar_subra/116/Default.aspx
Comment posted by Morten on Thursday, May 6, 2010 10:11 AM
DateTime.Parse will not work in all Culture settings, like in norwegian.
Comment posted by Suprotim Agarwal on Friday, May 7, 2010 3:50 AM
Miklos: Probably the initial load is where you see the flicker? Or is it for the entire run?

Morten: In that case, how about using it in conjuction with ParseExact?
Comment posted by Richard Fawcett on Thursday, December 9, 2010 6:18 AM
In addition to the above, in order to not get XML, and to allow the service to run from javascript, I had to uncomment the [ScriptService] attribute on the class. The comment added by Visual Studio to this attribute is cryptic. It has nothing to do with ASP.NET AJAX, but all javascript frameworks!
Comment posted by Luis Estrada on Thursday, December 30, 2010 11:02 AM
success: function (msg) {
            lBox.empty().append($.map(msg.d, function (elem, index) { return $('<option value="' + index + '">' + elem + '</option>'); }));
        }
Comment posted by mj on Tuesday, September 13, 2011 8:52 AM
Pretty sure Amber isn't a male name but good job
Comment posted by Grewal on Thursday, May 22, 2014 7:06 AM
Nice Post
Comment posted by John V on Tuesday, August 12, 2014 12:53 PM
You left off one important thing. Let's see you retrieve the selected value(s) of the listbox when that page is posted back.
Comment posted by mike on Wednesday, December 17, 2014 10:33 AM
Demo site does not work...

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook