-1

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.

Community
  • 1
  • 1
Lua Sheng
  • 83
  • 1
  • 1
  • 4
  • Make an ajax call to the backend code by providing the relevant data from the first dropdown. Then filter the other dropdowns data based on that particular value which has been passed. Finally return the data as Json and build you dropdowns using jQuery and fill the dropdowns by the data that has been returned to you – Izzy Nov 18 '16 at 18:25
  • Refer also [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) for a full implementation –  Nov 18 '16 at 20:41

1 Answers1

0

Well easiest way to do dropdown cascading should be a jquery ajax call. Once you select the 1st dropdown based on the selected id, do a json jquery ajax call get data required for the next dropdown and populate that. You may write a mvc json result action in controller for getting the data.