Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

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(.....
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
        });
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...