Three Ways to Populate a Select Element with ASP.NET MVC and jQuery

Posted by: Malcolm Sheridan , on 2/18/2010, in Category ASP.NET MVC
Views: 89314
Abstract: The following article demonstrates three ways to populate a select element using ASP.NET MVC and jQuery.
Three Ways to Populate a Select Element with ASP.NET MVC and jQuery
 
Sometimes I get asked how-to question on forums. I am going to dedicate some article to answering these questions. One common question is how do you populate a select element using MVC?  Well there are quite a few ways to do this, so I'll demonstrate the ways I like to do this. I'll be using jQuery 1.4 and you can download it here.
The server side code for this is simple. I've created a private method that will return a generic list of SelectListItems. Here it is:

 

C#
private static List<SelectListItem> GenerateNumbers()
{
      var numbers = (from p in Enumerable.Range(0, 20)
                      select new SelectListItem
                       {
                              Text = p.ToString(),
                              Value = p.ToString()
                        });
      return numbers.ToList();
}
VB.NET (converted using a tool)
Private Shared Function GenerateNumbers() As List(Of SelectListItem)
      Dim numbers = ( _
          From p In Enumerable.Range(0, 20) _
          Select New SelectListItem With {.Text = p.ToString(), .Value = p.ToString()})
      Return numbers.ToList()
End Function
That being done here the code to populate a select element.
Using Html.DropDownList
The first option is to use MVC HTML helpers method Html.DropDownList. This takes a collection and adds it to your select element. Here's the code including the action method:
C#
public ActionResult Index()
{
      ViewData["Numbers"] = GenerateNumbers();
      return View();
}
<%= Html.DropDownList("Numbers",(IEnumerable<SelectListItem>)ViewData["Numbers"]) %>
VB.NET (converted using a tool)
Public Function Index() As ActionResult
      ViewData("Numbers") = GenerateNumbers()
       Return View()
End Function
 
What's happening is in the action, Index, I'm adding the list of numbers to the ViewData, then that is automatically returned to the view. To add the collection to the select element, I'm casting it to an IEnumerable<SelectListItem> collection:
C#
(IEnumerable<SelectListItem>)ViewData["Numbers"]
VB.NET (converted using a tool)
CType(ViewData("Numbers"), IEnumerable(Of SelectListItem))
Nice and simple. But what if you need to populate the select element using Ajax? Read on and find out.
Using jQuery, Ajax and an Array
The second way to populate a select element is by using jQuery's Ajax function. Here's the code below complete with the action method:
C#
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetListViaJson()
{
      return Json(GenerateNumbers());
}
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#Button1").click(function(e) {
                e.preventDefault();
                var data = [];
                $.getJSON("/Home/GetListViaJson", null, function(data) {
                    data = $.map(data, function(item, a) {
                        return "<option value=" + item.Value + ">" + item.Text + "</option>";
                    });
                    $("#Select1").html(data.join(""));
                });
            });           
        });   
</script>
 
VB.NET (converted using a tool)
Public Function GetListViaJson() As JsonResult
      Return Json(GenerateNumbers())
End Function
 
To begin with the action has to be decorated with the AcceptVerbs attribute to allow it to respond to HTTP Get requests:
 
 
[AcceptVerbs(HttpVerbs.Get)]
 
 
Then I use $.getJSON to make an ajax call and return the data as an JSON object:
 
$.getJSON("/Home/GetListViaJson", null, function(data) {
 
I then create an array and use jQuery's map function to iterate over the array, create each option element and add the text and value:
 
data = $.map(data, function(item, a) {
      return "<option value=" + item.Value + ">" + item.Text + "</option>";
});
 
Then lastly I add the array to the select element:
 
$("#Select1").html(data.join(""));
 
This is good, but there a better way to add these elements and that's using jTemplates.
 
Using jQuery, Ajax and jTemplates
 
jTemplates makes this task even simpler, and better still, it decouples the HTML from the JavaScript into a .htm file. jTemplates is a template engine for JavaScript. The action is still the same as above, so let's jump into the JavaScript:
 
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript" src="http://jtemplates.tpython.com/jTemplates/jquery-jtemplates.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() { 
            $("#Button2").click(function(e) {
                e.preventDefault();               
                $.getJSON("/Home/GetListViaJson", null, function(data) {
                    $("#Select2").setTemplateURL("/Templates/DropDownList.htm").processTemplate(data);
                });
            });
        });   
</script>
 
As you can see the code above is much simpler. I am still retrieving the data via ajax and JSON, but once I have it, I pass it onto jTemplates and it renders it for me:
 
$("#Select2")
      .setTemplateURL("/Templates/DropDownList.htm")
      .processTemplate(data);
});
 
Here's the DropDownList.htm file:
 
{#foreach $T as data}
    <option value="{$T.data.Value}">{$T.data.Text}</option>   
{#/for}
 
The syntax above is specific to jTemplates. What I really like about using jTemplates is that it decouples the HTML from the JavaScript. Brilliant!
 
So I've shown you three ways to populate select elements using ASP.NET MVC and jQuery. Of course there are more ways to do this, but this is my preferred methods. The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Altaf Khatri on Tuesday, February 23, 2010 7:07 PM
Please refer to this article for populating HTML select list:
http://www.altafkhatri.com/Technical/How_to_bind_IList_with_MVC_Dropdownlist_box

Please refer to this article for handling postback with select list:
http://www.altafkhatri.com/Altaf/ASP_NET_MVC_Postback/Dropdownlist_Example/PostBack
Comment posted by Dejan.s on Tuesday, March 30, 2010 1:42 AM
Hi. thanks for the article, well written. I can't make this work tho, I even tried to copy your source code to a new project and it wont work. I got the jquery reference, code in homecontroler, and homeview.  Any ideas?
Comment posted by Dejan.s on Tuesday, March 30, 2010 1:43 AM
Hi. thanks for the article, well written. I can't make this work tho, I even tried to copy your source code to a new project and it wont work. I got the jquery reference, code in homecontroler, and homeview.  Any ideas?
Comment posted by Dejan.s on Tuesday, March 30, 2010 8:00 AM
Problem was that I used MVC 2. Not really sure what the difference is using JSON but I will look into it.
Comment posted by Malcolm Sheridan on Thursday, May 20, 2010 6:12 AM
@Dejan.s
By default in MVC2, actions that return a JsonResult don't respond automatically to HttpGet requests.  You need to add JsonRequestBehaviour to your action.  Like this:

return Json(null, JsonRequestBehavior.AllowGet);
Comment posted by Prashant k on Thursday, September 23, 2010 2:23 AM
Thanks..its helpful for me
Comment posted by Mictian on Friday, January 27, 2012 8:47 AM
Hi Malcolm, I've tried your second example and I think that you need to specify that the json result allows get. something like:
"return Json(data, JsonRequestBehavior.AllowGet);"
Anyway, excellent post!!
Comment posted by Nick McDermaid on Monday, September 24, 2012 3:44 AM
Your very first example turned three days desapit into triumph, Thankyou.
Comment posted by Michael on Friday, January 17, 2014 12:52 AM
OutStanding example dear, its really useful. Ya there are many ways to do that but this would be the basic example... really superb. Thumbs up for you.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel