A cascading drop-down list is a series of dependent DropDownList which one DropDownList control depends on the parent or previous DropDownList and items in the DropDownList are populated based on an item that is selected by the user from another DropDownList.The term Cascading a DropDownList refers to a process where a single of multiple DropDropList gets data based on the value picked from another DropDownList. Now I am working on .NET Core web application and I want to fetch Second dropdown list based on value of first dropdown list using ajax without page loading.
Download Source Code : https://findandsolve.com/source-code/code-cascading-dropdowns-with-aja-in-razoe-pages-using-dot-core-5
By the end of this article, we will learn the following:
- Creating .NET 5 an application.
- Installing Package for Entity framework core.
- Database Connection(ConnectionString)-appsetting.json.
- Create Category and SubCategory Class.
- Adding DbSet for Category, SubCategory in MyDBContext class.
- New Service in Startup.cs class for injecting dependency.
- Add/Update Migration.
- Return JSON format from Controller.
- INSERT INTO Scrpt in n SQL.
- Getting Data from Database using Entity framework core.
- JavaScript/AJAX and JSON.
- Bind data in DropDownList in using razor.
- Filter Second DropDown data by selected first DrowDown value.
Create Application in .NET 5
Step 1.
Open Visual Studio 2019 from the start page and click on the New Project link.
Step 2.
Step 3.
Finally,I have Created new Project CascadingExam as given below.
Installing Package for Entity framework core
To install the package, just right click on the project CascadingExample and then select Manage NuGet package. The below dialog of the NuGet Package Manager will pop up.In the pop up browse tab,search the type of “Microsoft.EntityFrameworkCore.SqlServer” in the search box and just click on the Install button.I am going to install lilke as
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Database Connection-appsetting.json.
After adding a reference Microsoft.EntityFrameworkCore.SqlServer, now open appsetting.json and past code as given below.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"ConnectionStrings": {
"windowsAuthentication": true,
"DefaultConnection": "Data Source=DESKTOP-9KQH8Q0;Database=Demo;Trusted_Connection=True;"//this is windows athenticaiton
//"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=Demo;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
}
},
"AllowedHosts": "*"
}
Create Category and SubCategory Class.
For adding a new folder, just right click on the project CascadingExample, then choose Add from the menu that pops up, and inside that choose New Folder now I am going to create new folder 'Entities'.like as give below.
For adding a New entity model "Cateogry", just right click on the Entities folde which already created as given above.Then, select Add >> Class. An "Add New Item" dialog will pop up with the default class selected.Name the class as Cateogry and click on the Add button.
and
Open under Entities->Category.cs class and paste this code as given below.
public class Category { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CategoryId { get; set; } public string CategoryName { get; set; } }
Creae again new Class name SubCategory.cs under Entities folder like as above created Category.cs class.
Open SubCategory.cs clas and past this code as given below.
public class SubCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SubCategoryId { get; set;}
public int CategoryId { get; set; }
public string SubCategoryName { get; set; }
}
Note
[Key]: Key represent primary key like as sql table.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]: represent auto increment identity(1,1) like as sql table
Creae new Class name MyDBContext.cs under Entities folder like as above like as Category.cs and SubCategory.cs class.MyDBContext class, next, we are going to inherit the DbContext class.
After inheriting with DbContext, next we are creating a constructor which takes DbContextOptions as an input parameter and also inherits the base class constructor (: base(options)) [DbContext].
Now I have three class Category.cs,SubCategory.cs and MyDBContent.cs under the Entities folder like as image.
Adding DbSet for Category, SubCategory in MyDBContext class.
Open MyDBContext.cs from Entities folder and past this code as given below.
public class MyDBContent:DbContext
{
private IConfigurationRoot _config;
public MyDBContent(IConfigurationRoot config, DbContextOptions options) : base(options)
{
_config = config;
} public DbSet<Category> Category { get; set; }
public DbSet<SubCategory> SubCategory { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);//connection string get by appsetting.json }
}
New Service in Startup.cs class for injecting dependency
Open Startup.cs and past this code as given below.
Startup.cs
public class Startup
{
private IConfigurationRoot _config;
public Startup(IConfiguration configuration,IWebHostEnvironment env) {
Configuration = configuration;
var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
_config = ConfigBuilder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_config);
services.AddDbContext<MyDBContent>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else {
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.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Add/Update Migration
After that we are ready to Migration our project.EF Core migrations are a set of commands which you can execute in NuGet Package Manager Console or in dotnet Command Line Interface (CLI).More Details :https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli.
This is code first application so we are ready to migration our First project.Select View > other Windows >Package Manager Console given below.
After click Package Manager Console,At this point of time, the Package Manager Console will have the following structure.And Type "Add-Migration Initial" as given Image
After Add-Migration Initail,Show the result on Package Manager Console given below.After Migration is success then you must update your database Update-Database like given below.
After update database migration
In the Demo Databasse
INSERT INTO Scrpt in SQL
i want to add rows in my Category table.Now I am showing how to insert data or row in sql table as given below.
INSERT INTO Category VALUES('Category 1')
INSERT INTO Category VALUES('Category 2')
INSERT INTO Category VALUES('Category 3')
And also add rows in my second table SubCategory as given below.
Insert data in SubCategory Under Category 1
INSERT INTO SubCategory VALUES(1,'SubCategory 1')
INSERT INTO SubCategory VALUES(1,'SubCategory_1')
INSERT INTO SubCategory VALUES(1,'SubCategory1')
Insert data in SubCategory Under Catetgory 2
INSERT INTO SubCategory VALUES(2,'SubCategory 2') INSERT INTO SubCategory VALUES(2,'SubCategory_2') INSERT INTO SubCategory VALUES(2,'SubCategory2')
Insert data in SubCategory Under Catetgory 3
INSERT INTO SubCategory VALUES(3,'SubCategory 3') INSERT INTO SubCategory VALUES(3,'SubCategory_3') INSERT INTO SubCategory VALUES(3,'SubCategory3')
Getting Data from Database using Entity framework core
Open Default Controller HomeController.cs and replce code as given below.
ViewBag: For more details Click Me
Bind data in DropDownList in using razor.
Open Index page under Views->Home->Index.cshtml and add this code as given below.
HTML
@model CascadingExample.Entities.SubCategory
@{
ViewData["Title"] = "Home Page";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-2 form-group">
<select asp-for="CategoryId" class="form-control" id="categoryId"
asp-items="@(new SelectList(@ViewBag.CategoryList,"CategoryId","CategoryName"))"></select>
</div>
<div class="col-sm-2 form-group">
<select asp-for="SubCategoryId" class="form-control"id="subCategoryId"></select>
</div>
</div>
</div>
JavaScript/AJAX and JSON
JavaScript in index.cshtml page
<script type="text/javascript">
$(document).ready(function () { getSubCategoryListByCategoryId(); })
$("#categoryId").change(function () { getSubCategoryListByCategoryId(); });
var getSubCategoryListByCategoryId = function () { $.ajax({ url: '@Url.Action("GetSubCategoryByCategoryId","Home")', type: 'GET', data: { categoryId:$('#categoryId').val(), }, success: function (data) { $('#subCategoryId').find('option').remove() $(data).each( function (index, item) { $('#subCategoryId').append('<option value="' + item.subCategoryId + '">' + item.subCategoryName + '</option>') }); }, error: function () {
} }); }
</script>
$(document).ready(function () {} : will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Finally we have completed the "Cascading Dropdown List in .NET 5". Thanks for reading the article. If you like it, please share it.
Comments