Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Html.DropDownList populated by Ajax call to controller?

I wanted to create an editor template for a field type that is represented as a dropdownlist. In the definition of the editor template I would like to populate the DropDownList using a call to an action on the controller returning the results as JSON - Any ideas how to do this?

E.g something like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TheFieldType>" %>
<%= Html.DropDownList(.....
like image 873
UpTheCreek Avatar asked Sep 30 '10 11:09

UpTheCreek


People also ask

How pass dropdown selected value to controller in MVC using Ajax?

You need to select the select using the ID which requires the # in your selector, and val() is the jQuery method to get the select's value and nothing else as shown below. Show activity on this post. Show activity on this post.

How fetch data from database in DropDownList in Ajax?

First, Make dropdown in you HTML and create an Ajax method and pass the dropdown selected value into it. Then keep this data in your PHP sides and execute your SQL query and show the result on your HTML page. Now you could execute your SQL the $id variable. Show activity on this post.


2 Answers

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);
        });
    });
});
like image 60
Darin Dimitrov Avatar answered Oct 02 '22 22:10

Darin Dimitrov


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.

like image 2
Frank Bonnet Avatar answered Oct 03 '22 00:10

Frank Bonnet