Lua Sheng Lua Sheng - 18 days ago 9
Ajax Question

Chained dynamically populated dropdowns in ASP.NET MVC?

I have a problem with dynamically populated dropdowns on ASP.NET MVC5.
Let's simplify my data:

public class Country {
public int Id {get;set;}
public string InternationalCode {get;set;}
public string Name {get;set;}
public virtual ICollection<City> Cities {get;set;}
...
}
public class City{
public int Id {get;set;}
public int CountryId {get;set;}
public string Name {get;set;}
...

}


In my controller I pass countries to ASP.NET's standard dropdown helper and show it on the view - no problems here, thanks to this post. My question arise here - let's say that I have another dropdown just below the first one. How can it be dynamically filled based on first dropdown's result?
I defined in my Controller the following method :

public IEnumerable<City> GetCitiesFromCountry(int countryId) => db.Countries.Find(countryId).Cities;


How to call it without reloading the page? I can't use some advanced technics like Angular\Knockout - only JavaScript\jQuery\Ajax allowed.

Answer

You mean to say cascading dropdown list- filling the second dropdown based on value selected from first dropdown.

Then try this link asp.net MVC cascading dropdown lists