Ajax Dropdown

the ajax dropdown can be called in many ways:
@Html.AjaxDropdownFor(o => o.Hobby)
@Html.EditorFor(o => o.Foobar)
@Html.AjaxDropdownFor(o => o.Person2, controller:"PersonAjaxDropdown") 
It requires a controller to get it's data from. By default it looks for a controller with the same name as the property + AjaxDropdown, you can specify a different controller to be used using the helper's parameters or by applying the AjaxDropdown attribute on the property

The controller should have an Action GetItems(key) that should return a Json result made from an IEnumerable<SelectListItem>
    public class CountryAjaxDropdownController : Controller
        public ActionResult GetItems(int? key)
            var list = new List<SelectListItem> {new SelectListItem { Text = "not selected", Value = "" }};            
            list.AddRange(countryRepo.GetAll().Select(o => new SelectListItem
                Text = o.Name,
                Value = o.Id.ToString(),
                Selected = o.Id == key
            return Json(list);

Binding to an editor using ParentId

you can bind the dropdown to an editor so that when the parent's value gets changed the GetItems action will be called and the value of the parent will be sent to this action, so it would be something like this:
<%=Html.AjaxDropdown("Show") %>
<%=Html.AjaxDropdown("Character", parentId: "Show") %> 
and the controller for Character:
public class CharacterAjaxDropdownController : Controller
  // each time this action get's called the value of parent (Show) will be sent here
  // and each time parent's value is changed this action gets called
  public ActionResult GetItems(int? key, int? parent)
if you're using the EditorFor helper you can use AjaxDropdownAttribute to specify ParentId

Using data when you need "many parents"

so, if one parentId is not enough you can use "data" instead, like this:
<%=Html.AjaxDropdown("Chef") %>
<%=Html.Lookup("Meals", multiselect: true) %>
<input type="text" id="Foo" name="Foo" value="hi" />
<%=Html.AjaxDropdown("Dinner", data: new Dictionary<string,string>{ { "ChefId", "chef" }, {"Meals","meals"}, {"Foo","fooText"} }) %>
and in the controller
public class DinnerAjaxDropdownController : Controller 
  public ActionResult GetItems(int? key, int? chef, IEnumerable<int> meals, string fooText)

you can also send predefined values to the controller, look here: AwesomeParameters

Last edited May 12, 2011 at 11:53 AM by o, version 5


No comments yet.