ASP.NET MVC Html.DropDownList populated by Ajax call to controller?
In the editor template provide an empty dropdown:
<%= Html.DropDownListFor(
x => x.PropertyToHoldSelectedValue,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
%>
Then setup a controller action that will return the values:
public class FooController: Controller
{
public ActionResult Index()
{
return Json(new[] {
new { Id = 1, Value = "value 1" },
new { Id = 2, Value = "value 2" },
new { Id = 3, Value = "value 3" },
}, JsonRequestBehavior.AllowGet);
}
}
And then populate the values using AJAX:
$(function() {
$.getJSON('/foo/index', function(result) {
var ddl = $('#foo');
ddl.empty();
$(result).each(function() {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
});
});
I know this post is a few years old but I found it and so might you. I use the following solution and it works very well. Strong typed without the need to write a single line of Javascript.
mvc4ajaxdropdownlist.codeplex.com
You can download it via Visual Studio as a NuGet package.