Cascading Dropdown List Using PrimaryKey and ForeignKey
Url:-https://www.findandsolve.com/articles/cascading-dropdownlist-in-net-core-5
Reference:-
"Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0"
"Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"
Controllers[Folder]
HomeController.cs
using CascadingExample.Entities;
using CascadingExample.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly MyDBContent _con;
public HomeController(ILogger<HomeController> logger, MyDBContent con)
{
_logger = logger;
_con = con;
}
public IActionResult Index()
{
ViewBag.CategoryList = _con.Category.ToList();
return View();
}
public JsonResult GetSubCategoryByCategory(int categoryId)
{
var data = _con.SubCategory.Where(x => x.CategoryId == categoryId).ToList();
return Json(data);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Entities[Folder]
Category.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Entities
{
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
}
MyDBContent.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Entities
{
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
}
}
}
SubCategory.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample.Entities
{
public class SubCategory
{
[Key]
//Represent autoincrement id
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SubCategoryId { get; set; }
public int CategoryId { get; set; }
public string SubCategoryName { get; set; }
}
}
Views[Folder]
Home
Index.cshtml
@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>
<script type="text/javascript">
$(document).ready(function () {
getSubCategoryListByCategoryId();
})
$("#categoryId").change(function () {
getSubCategoryListByCategoryId();
});
var getSubCategoryListByCategoryId = function () {
$.ajax({
url: '@Url.Action("GetSubCategoryByCategory", "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>
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=CHETUIWK1689\\MSSQL2019;Database=Demo;Trusted_Connection=True;MultipleActiveResultSets=True"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Startup.cs
using CascadingExample.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CascadingExample
{
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();
services.AddDbContext<MyDBContent>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext<MyDBContent>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// 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");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
0 Comments