views:

58

answers:

1

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(.....
+2  A: 

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);
        });
    });
});
Darin Dimitrov
This looks great - I'll give it a try and get back.
UpTheCreek