04 February 2023

How to Create Cascading Dropdown List | Country, State and City Cascading Example in ASP.NET CORE

 


How to Create Cascading Dropdown List | Country, State and City Cascading Example in ASP.NET Core MVC

In this tutorial we have explained how to create cascading(Country, State and City) drop down list in ASP.NET Core MVC and then populate drop down list from database. We have used Entity Framework Core Code First approach with JQuery and Ajax to populate drop down list items.


Cascading dropdown list allows you to select an option in one dropdown list, and based on that selection, another dropdown list is dynamically updated with new options. In this article, we'll show you how to create cascading dropdown lists in ASP.NET Core MVC.

Step 1: Setting up the Project

1. Open Visual Studio and create a new ASP.NET Core web application.
2. Choose the Model-View-Controller (MVC) template, and select the latest version of ASP.NET Core.
3. After the project is created, go to the Package Manager Console and install  required packages.

Step 2: Creating the Model

1. In the Models folder, create a new classes for Country, State and City.
2. In this class, add required properties.

Step 3: Creating the DAL and DbContext

1. Create a folder called DAL and create a DbContext as MyAppDbContext and add all the tables dataset here.

Step 4: Creating the Connectionstring

1. Create SQL server database connection string in Appsettings.json

Sample:
"ConnectionStrings": {
    "DefaultConnection": "server=MYPC\\SQLDEMO;database=DEMO;integrated security=true; trustServerCertificate=true"
  }

Step 5: Register the Connectionstring and DBContext

1. Register the connectionstring and DBContext here.

Sample:
builder.Services.AddDbContext<MyAppDbContext>(options=> options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


Step 6: Creating the Controller

1. In the Controllers folder, create a new controller.
2. In this controller, add the action methods.

Step 7: Creating the View

1. Create a View.
2. Design the view to display Country, State and City drop-down.


Step 8: Creating a Javascript file

1. Create a javascript file to store function to read the data of Country, State and City from database by using JQuery and Ajax.

2. Write JQuery functions by using AJAX to read the data.

 Step 9: Run the application and test.

Note: Any issues, please watch the video which is provided in the top.

No comments:

Post a Comment