In this article, we will learn How to Create Cascading/Dependent Dropdown List in Asp.net Core MVC C# . In previous article we had discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/.
Prerequisites
- Download and install .Net Core 6.0 SDK from here
- Download and Install Microsoft Visual Studio 2022 from here
- Sql-Server
Create an ASP.NET Core MVC Project
Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.
Enter project name and click create.
Install NuGet Packages
- Microsoft Entity Framework Core Sql Server.
- Microsoft Entity Framework Core Tools
Configure appsettings.json
There are two connection string one is SQL Server and another one is excel .
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "sqlconnection": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true", }, "AllowedHosts": "*" }
Create Model
Create Model class and DbContext Class.
//Country.cs
using System.ComponentModel.DataAnnotations; namespace Asp.netcore_Tutorials.Models { public class Country { [Key] public int countryId { get; set; } public string countryName { get; set; } } }
State.cs
using Microsoft.EntityFrameworkCore.Metadata.Internal; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Asp.netcore_Tutorials.Models { public class State { [Key] public int StateId { get; set; } public string stateName { get; set; } public int CountryId { get; set; } [ForeignKey (nameof(CountryId))] public virtual Country Country { get; set; } } }
City.cs
using Microsoft.EntityFrameworkCore.Metadata.Internal; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Asp.netcore_Tutorials.Models { public class City { [Key] public int cityId { get; set; } public string cityName { get; set; } public int CountryId { get; set; } public virtual Country country { get; set; } public int stateId { get; set; } public virtual State state { get; set; } } }
CustDbcontext.cs
//CustDbcontext.cs using Microsoft.EntityFrameworkCore; namespace Asp.netcore_Tutorials.Models { public class CustDbcontext :DbContext { public CustDbcontext(DbContextOptions<CustDbcontext> options):base(options) { } public virtual DbSet<Country> Countries { get; set; } public virtual DbSet<State> States { get; set; } public virtual DbSet<City> Citys { get; set; } } }
Create Interface and Concrete Class
Interface ICustomer.cs
using System.Data; namespace Asp.netcore_Tutorials.Repository { public interface IInventory { Task<IEnumerable<Country>> Getcountries(); Task<IEnumerable<State>> Getstates(); Task<IEnumerable<City>> Getcitys(); Task<IEnumerable<State>> GetStatesByCountryId(int countryId); Task<IEnumerable<City>> GetCityById(int stateId); } }
Concrete Class Customerdetail.cs
using Microsoft.AspNetCore.Http; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.IO; namespace Asp.netcore_Tutorials.Repository { public class Inventory : IInventory { private readonly CustDbcontext _IvenContext; public Inventory(CustDbcontext custDbcontext) { _IvenContext = custDbcontext; } public async Task<IEnumerable<City>> Getcitys() { return await _IvenContext.Citys.ToListAsync(); } public async Task<IEnumerable<Country>> Getcountries() { return await _IvenContext.Countries.ToListAsync(); } public async Task<IEnumerable<City>> GetCityById(int stateId ) { if (stateId != 0 ) { return await _IvenContext.Citys.Where(c => c.stateId == stateId).ToListAsync(); } return null; } public async Task<IEnumerable<State>> GetStatesByCountryId(int countryId) { if (countryId != 0) { return await _IvenContext.States.Where(s => s.CountryId == countryId).ToListAsync(); } return null; } public async Task<IEnumerable<State>> Getstates() { return await _IvenContext.States.ToListAsync(); } } }
Configure Program.cs
using Asp.netcore_Tutorials.Models; using Asp.netcore_Tutorials.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System.Configuration; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<CustDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection"))); builder.Services.AddScoped<ICustomer,CustomerDetail>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Migration
Add-Migration 'Initial-Create' Update-Database
Create Controller
InventoryController.cs
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Asp.netcore_Tutorials.Repository; using Microsoft.AspNetCore.Mvc.Rendering; namespace Asp.netcore_Tutorials.Controllers { public class InventoryController : Controller { // GET: InventoryController private readonly IInventory _Ivencontext; public InventoryController(IInventory ivencontext) { _Ivencontext = ivencontext; } public ActionResult Index() { ViewBag.Countries = _Ivencontext.Getcountries().Result; ViewBag.State = _Ivencontext.Getstates().Result; ViewBag.Cities = _Ivencontext.Getcitys().Result; return View(); } // GET: InventoryController/State/5 public JsonResult GetState(int countryid) { List<SelectListItem> getState = new List<SelectListItem>(); var Getstateresult = _Ivencontext.GetStatesByCountryId(countryid).Result; if (countryid != 0) { return Json(Getstateresult); } return null; } public JsonResult GetCity(int stateid) { List<SelectListItem> CityListItems= new List<SelectListItem>(); var getcityresult = _Ivencontext.GetCityById(stateid).Result; if (stateid != 0) { return Json(getcityresult); } return null; } } }
Customize View
index.cs
@{ ViewData["Title"] = "Home Page"; } <div class="row"> <div class="form-group"> <div class="col-sm-4"> <select name="Country" id="Country" class="form-select-lg" asp-items="@(new SelectList(ViewBag.Countries,"countryId","countryName"))"> </select> </div> </div> <div class="form-group"> <div class="col-sm-4"> <select name="State" id="State" class="form-select-lg"> </select> </div> </div> <div class="form-group"> <div class="col-sm-4"> <select name="City" id="City" class="form-select-lg"> </select> </div> </div> </div>
Jquery
<script src="~/lib/jquery/dist/jquery.js"></script> <script> var country_id=0; $(document).ready(function() { $('#Country').change(function () { country_id = $('#Country').val(); var items =''; $.ajax({ type: "POST", url: "/Inventory/GetState", data: { countryid: country_id }, dataType: "json", success: function (data) { $.each(data, function(k, option){ items += "<option value = '" + option.stateId + "'>" + option.stateName + " </option>"; }); $('#State').html(items); } }); }); $('#State').change(function () { state_id = $('#State').val(); var items = ''; $('#City').empty(); $.ajax({ type: "POST", url: "/Inventory/GetCity", data: { stateid: state_id }, dataType: "json", success: function (data) { $.each(data, function (k, option) { items += "<option value = '" + option.cityId + "'>" + option.cityName + " </option>"; }); $('#City').html(items); } }); }); }); </script>