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
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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