Dynamically populate lists by information from other conditions - MVC

Problem

Suppose we have a database with Customer entity which has Country and City attributes. For both these attributes we define the value editors which return the lists of available values (countries and cities correspondingly).

Now let's imagine a user adds a condition with Country attribute e.g. Country is equal to USA. After that they also add a condition with City attribute. Obviously, while Country is selected already we would like to see only the cities from that selected country.

Solution

To implement such functionality you we need to perform the following few steps:

  1. Define the value editor for City attribute as CUSTOMLIST with the following name: Cities.{{Customers.Country}} (Here Customers.Country is the ID of the Country attribute in Customer entity).

  2. Define a CustomListResolver handler in your EasyQueryController's constructor:

eqService.CustomListResolver = (listname) => {
                if (listname.StartsWith("Cities.")) {

                    string countryCode = listname.Substring("Cities.".Length);

                    if (code == "USA") {
                        return new List<ListItem> {
                            new ListItem("NY","New York"),
                            new ListItem("CH", "Chicago"),
                            new ListItem("ST","Seattle"),
                            new ListItem("LA", "LA")
                        };
                    }
                    else if (code == "UK") {
                        return new List<ListItem> {
                            new ListItem("OX","Oxford"),
                            new ListItem("LN","London"),
                            new ListItem("MN","Manchester"),
                            new ListItem("GL","Glasgow")
                        };
                    }
                }
                return Enumerable.Empty<ListItem>();
            };

What's happening here?

The client-side script automatically recognizes the list names with that special parameter ({{Attribute ID}}) and replaces it with a particular value if there is a condition with this attribute in our query. After that, you can get that value on the server side and use it to filter the result list.

In our example we just fill the list "manually" but, of course, you can execute some SQL query with a parameter there to get the list of cities.