Friday, June 12, 2026

ASP.NET Core Razor Pages Cascading Dropdowns: Selection Change

Create ASP.NET Core Razor Pages applicaion to display Cascading Dropdowns as shown below.
Step1. Add Razor Pages service in Program class file.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();

var app = builder.Build();

app.UseDeveloperExceptionPage();

app.UseRouting();

app.MapRazorPages();

app.Run();
Step2. In the Razor front page, create a list of countries. Convert this list into IEnumerable<SelectListItem> type data. Use fetch API for HTTP GET which returns a list of states from server to the client when country name is changed.
@page
@model CascadingDropdownsRazorPages.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    List<string> list = new List<string>()
    {
        "India", "France","Pakistan","Germany"
    };

    // convert List<string> into IEnumerable<SelectListItem>
    IEnumerable<SelectListItem> countries = list.ConvertAll(x =>
    {
        return new SelectListItem()
                {
                    Text = x,
                    Value = x.ToLower(),
                    Selected = false
                };
    });

}

<style>
    .tbl {
        border: solid red 5px;
        margin: auto;
        width: 25%;
        padding: 10px;
    }
</style>
<div align="center">
    <h1>ASP.NET Core Razor Pages Cascading Dropdowns: Selection Change</h1>
    <h4>Select a country of your choice from 1st dropdown to get its states in another dropdown.</h4>
</div>
<div class="tbl">
    <span id="msg" style="text-align:center"></span>
    <table border="0" cellpadding="5">
        <tr>
            <td>
                <select id="source_ddl" asp-items="@countries"></select>
            </td>
        </tr>
        <tr>
            <td>
                <select id="target_ddl" required></select>
            </td>
        </tr>
    </table>
</div>

<script>
    (function(){
        const source = document.getElementById('source_ddl');
        const target = document.getElementById('target_ddl');
        source.addEventListener('change', async function(event){
            event.preventDefault();
            document.getElementById("msg").innerHTML = "<h3>You selected " + source.value.toUpperCase() + "</h3>";
            console.log("changed the selection...");
            console.log("source...", source.value);
            // remove old items from target dropdown
            target.options.length=0;
            // execute the fetch API
            fetch('/?handler=ChangedCountry&country=' + source.value,{
                method:'GET'
            }).catch(err=> console.log("Some error occured: "+err))
            .then(response =>{
                return response.json();
            }).then(states => {
                console.log('states:',states);
                // receives a list of states from server
                // populate each state as option to target dropdown
              states.forEach(state=>{
                    let opt = document.createElement('option');
                    opt.setAttribute('value', state);
                    opt.innerHTML= state;
                    target.append(opt);
                })
            })
        });
    })();
</script>
Step3. Write the backend logic for event handling when country name is changed by user.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.Json; // for serialization

namespace CascadingDropdownsRazorPages.Pages
{
    public class IndexModel : PageModel
    {
        List<string> states = new List<string>();
        public async Task<ActionResult> OnGetChangedCountry(string? country)
        {
            await Task.Delay(1);
            switch (country)
            {
                case "india":
                    {
                        states.Add("India1");
                        states.Add("India2");
                        states.Add("India3");
                        states.Add("India4");
                    }
                    break;
                case "france":
                    {
                        states.Add("France1");
                        states.Add("France2");
                        states.Add("France3");
                        states.Add("France4");
                    }
                    break;
                case "pakistan":
                    {
                        states.Add("Pakistan1");
                        states.Add("Pakistan2");
                        states.Add("Pakistan3");
                        states.Add("Pakistan4");
                    }
                    break;
                case "germany":
                    {
                        states.Add("Germany1");
                        states.Add("Germany2");
                        states.Add("Germany3");
                        states.Add("Germany4");
                    }
                    break;
                default:
                    break;
            }
            // list object is serialized
            return new JsonResult(states);
        }
    }
}
Next:

No comments:

Post a Comment

Hot Topics