Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MarshalOfficial/60fa35e7f3396cb6ace2a5b49f644c8c to your computer and use it in GitHub Desktop.
Save MarshalOfficial/60fa35e7f3396cb6ace2a5b49f644c8c to your computer and use it in GitHub Desktop.
Countries and cities drop downs manipulation in asp.net razor pages project

Assuming you have a Razor Page named Index.cshtml, here's how you can implement the dynamic population of cities based on the selected country using AJAX and jQuery:

  1. Design the UI: In your Index.cshtml, create two dropdown lists - one for countries and one for cities:

    <select id="countryDropdown">
        <option value="">Select Country</option>
        <!-- Populate countries dynamically if needed -->
    </select>
    
    <select id="cityDropdown">
        <option value="">Select City</option>
        <!-- Cities will be populated dynamically based on selected country -->
    </select>
  2. Implement AJAX Call: Use jQuery to make an AJAX call to fetch cities based on the selected country. Place this script either at the bottom of your Index.cshtml file or in a separate JavaScript file:

    <script>
    $(document).ready(function() {
        $('#countryDropdown').change(function() {
            var selectedCountry = $(this).val();
            $.ajax({
                url: '/Index?handler=GetCities', // Handler to fetch cities
                method: 'GET',
                data: { country: selectedCountry },
                success: function(response) {
                    $('#cityDropdown').empty(); // Clear existing options
                    $.each(response, function(index, city) {
                        $('#cityDropdown').append($('<option>').text(city).attr('value', city));
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                }
            });
        });
    });
    </script>
  3. Handle AJAX Request in PageModel: In your Index.cshtml.cs, implement the OnGetGetCities handler to handle the AJAX request and return cities based on the selected country:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using System.Collections.Generic;
    
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
            // Initialize your page
        }
    
        public JsonResult OnGetGetCities(string country)
        {
            // Implement logic to fetch cities based on the selected country
            List<string> cities = GetCitiesByCountry(country); // Dummy function, replace with your logic
            return new JsonResult(cities);
        }
    
        // Dummy function to return cities based on country (replace with actual logic)
        private List<string> GetCitiesByCountry(string country)
        {
            // Your logic to fetch cities based on country goes here
            // This is just a placeholder, replace it with actual data retrieval logic
            List<string> cities = new List<string>();
            if (country == "USA")
            {
                cities.Add("New York");
                cities.Add("Los Angeles");
                cities.Add("Chicago");
            }
            else if (country == "UK")
            {
                cities.Add("London");
                cities.Add("Manchester");
                cities.Add("Birmingham");
            }
            // Add more countries and cities as needed
            return cities;
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment