BMills BMills - 1 year ago 62
jQuery Question

assign selectlist based on another

My view model looks like this:

public IList<TeamCategory> TeamCategories { get; set; }
public IEnumerable<SelectListItem> TeamCategoriesList { get; set; }
public IList<CategoryInput> CategoryInputs { get; set; }

public class CategoryInput
public string CategoryName { get; set; }
public IEnumerable<SelectListItem> VenueList { get; set; }


foreach (var teamCategory in model.TeamCategories)
var categoryInput = new CategoryInput()
CategoryName = teamCategory.Name,
VenueList = teamCategory.Venues.Select(x => new SelectListItem()
Value = x.Id,
Text = x.Address



@Html.DropDownList("TeamCategory", Model.TeamCategoriesList, new {@id = "categorieslist"})

@Html.DropDownList("Venue", new List<SelectListItem>(), new {@id = "venuelist" })

So it starts off with teamcategories list being populated, and an empty venue list, then when I change the category, I'd like the venue list to be updated to the list associated with that category as can be seen from the query.

I've started the event listener, but after that I'm at a loss:

$('#categorieslist').change(function() {

function AssignVenues() {
var category = $('#categorieslist').val();


Answer Source

You need to listen to the change event on the TeamCategory select element,get the selected option value and make an ajax call to your server where you will receive the selected team category id ,get venues for that category id and return the result in JSON format.

@section Scripts


         var teamCategoryId=$(this).val();
         var venues="";

              venues+="<option value='"+b.Value+"'>"+b.Text+"</option>";



Assuming you have a GetVenues method in your HomeController which returns a list of SelectListItem's

public ActionResult GetVenues(int id)
   var list=new List<SelectListItem>();
   // I am hard coding 2 venues. 
   // You may replace it with your real data for the id passed in.

   list.Add(new SelectListItem { Value="1", Text="Ann Arbor"});
   list.Add(new SelectListItem { Value="2", Text="Detroit"});

   return Json(list,JsonRequestBehaviour.AllowGet);