Cascading dropdown in Asp.Net Core MVC using jQuery

In this article, I have explained how to create Cascading Dropdown in asp.net core MVC using jQuery.

What is Cascading Dropdown?

  •  Normally cascading dropdown means filling the second dropdown based on the first dropdown.

Step 1: First Create MVC Application.

Step 2: Then Install the Above packages.


Step 3: Create Classes In Model Folder .

Subject Class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Models
{
    public class Subjects
    {
        [Key]
        public int SubjectId { get; set; }

        public string SubjectName { get; set; }

    }
}

Topic Class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Models
{
    public class Topic
    {
        [Key]
        public int TopicId { get; set; }

        public string TopicName { get; set; }

        [Display(Name = "Subjects")]
        public virtual int SubjectId { get; set; }

        [ForeignKey("SubjectId")]
        public virtual Subjects Subjects  { get; set; }


    }
}

Chapter Class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Models
{
    public class Chapter
    {
        [Key]
        public int ChapterId { get; set; }

        public string ChapterName { get; set; }

        [Display(Name = "Topic")]
        public virtual int TopicId { get; set; }

        [ForeignKey("TopicId")]
        public virtual Topic Topic { get; set; }
    }
}

Step 4: Create DemoDbContext.

using Cascading_Dropdown.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown
{
    public class DemoDbContext:DbContext
    {
        public DemoDbContext(DbContextOptions<DemoDbContext> options):base(options)
        {

        }

        public DbSet<Subjects> Subjects { get; set; }
        public DbSet<Topic> Topic { get; set; }
        public DbSet<Chapter> Chapter { get; set; }
    }
}

Step 5: appsetting.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=VISION-029\\SQLEXPRESS;Initial Catalog=DemoDropdown;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
       {
           services.AddControllersWithViews();
           services.AddDbContext<DemoDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
           services.AddScoped<IDropdownDemoService, DropdownDemoService>();
       }

Step 6: Give Command for the package console.

  • Enable-Migrations
  • Add-Migration MyMigration
  • Update-database

Step 7: Then Create one Interface DropdownDemoService.

using Cascading_Dropdown.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Services
{
    public interface IDropdownDemoService
    {
        List<Subjects> GetSubject();
        List<SelectListItem> GetSubjectId(int Id);
        List<SelectListItem> GetTopicId(int Id);
    }
}

Step 8: Implement Interface in your service.

using Cascading_Dropdown.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Services
{
    public class DropdownDemoService : IDropdownDemoService
    {
        private readonly DemoDbContext _demoDbContext;

        public DropdownDemoService(DemoDbContext demoDbContext)
        {
            _demoDbContext = demoDbContext;
        }
        public List<Subjects> GetSubject()
        {
            try
            {
                var data = _demoDbContext.Subjects.ToList();
                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }

        public List<SelectListItem> GetSubjectId(int Id) 
        {
            var topics = _demoDbContext.Topic.Where(x => x.SubjectId == Id).ToList();
            List<SelectListItem> topic = new List<SelectListItem>();

            foreach (var item in topics)
            {
                topic.Add(new SelectListItem { Text = item.TopicName, Value = item.TopicId.ToString() });
            }

            return topic;
        }

        public List<SelectListItem> GetTopicId(int Id)
        {
            var chapters = _demoDbContext.Chapter.Where(x => x.TopicId == Id).ToList();
            List<SelectListItem> chapter = new List<SelectListItem>();

            foreach (var item in chapters)
            {
                chapter.Add(new SelectListItem { Text = item.ChapterName, Value = item.ChapterId.ToString() });
            }

            return chapter;
        }
    }
}

Step 9: Then also configure your service in the startup.cs file.

services.AddScoped<IDropdownDemoService, DropdownDemoService>();

Step 10: Then write the below code in your controller.

using Cascading_Dropdown.Models;
using Cascading_Dropdown.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Cascading_Dropdown.Controllers
{
    public class HomeController: Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IDropdownDemoService _dropdownDemoService;

        public HomeController(ILogger<HomeController> logger, IDropdownDemoService dropdownDemoService)
        {
            _logger = logger;
            _dropdownDemoService = dropdownDemoService;
        }

        public IActionResult Index()
        {
            return View();
        }

        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 });
        }

        //GetSubjectList
        public JsonResult GetSubjectList()
        {
            var res = _dropdownDemoService.GetSubject();
            return Json(res);
        }

        //GetTopicList
        [HttpGet]
        public JsonResult GetTopicList(int Id)
        {
            List<SelectListItem> Topic = new List<SelectListItem>();
            Topic = _dropdownDemoService.GetSubjectId(Id);
            return Json(Topic);
        }

        //GetChapterList
        [HttpGet]
        public JsonResult GetChapterList(int Id)
        {
            List<SelectListItem> Chapter = new List<SelectListItem>();
            Chapter = _dropdownDemoService.GetTopicId(Id);
            return Json(Chapter);
        }


    }
}

Step 11: _Layout.cshtml Add jquery script.

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    @*<title>@ViewData["Title"] - Cascading_Dropdown</title>*@
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
    <script src="~/js/jquery-3.4.1.js"></script>
</head>

Step 12: Then code for your view page.

@{
    ViewData["Title"] = "Cascading DropDown";
}

<style>
    .div_container 
    {
        background-color: whitesmoke;
        border-radius: 4px;
        text-align: center;
        padding: 13%;
    }
    .div_row 
    {
        font-weight: 600;
        background-color: lightgray;
        padding: 5%;
        font-size: 18px;
    }
</style>


<div class="container div_container">
    <div class="row div_row">
        <div class="col-md-12">
            <form>
                <div class="form-group">
                    <label class="float-left">Subjects:</label>
                    <select class="form-control" id="Subjects" name="Subjects" value="Subjects">
                    </select>
                </div>
                <div class="form-group">
                    <label class="float-left">Topics:</label>
                    <select class="form-control" id="Topics" name="Topics" value="Topics">
                    </select>
                </div>
                <div class="form-group">
                    <label class="float-left">Chapters:</label>
                    <select class="form-control" id="Chapters" name="Chapters" value="Chapters">
                    </select>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        $.ajax({
            url: "/Home/GetSubjectList",
            method: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data)
            {
                var items = '<option>Select Subject</option>';
                for (var i = 0; i < data.length; i++)
                {
                    items += "<option value='" + data[i].subjectId + "'>" + data[i].subjectName + "</option>";
                }

                $('#Subjects').html(items);
            }
        });
    });

    $("#Subjects").change(function () {
        event.preventDefault();
        $.ajax({
            url: "/Home/GetTopicList/" + $("#Subjects").val(),
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function (result)
            {
                var items = '<option>Select Topic</option>';
                for (var i = 0; i < result.length; i++)
                {
                    items += "<option value='" + result[i].value + "'>" + result[i].text + "</option>";
                }
                $('#Topics').html(items);
            }
        });
    });

    $("#Topics").change(function () {
        event.preventDefault();
        $.ajax({
            url: "/Home/GetChapterList/" + $("#Topics").val(),
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function (result)
            {
                var items = '<option>Select Chapters</option>';
                for (var i = 0; i < result.length; i++)
                {
                    items += "<option value='" + result[i].value + "'>" + result[i].text + "</option>";
                }
                $('#Chapters').html(items);
            }
        });
    });
</script>

Step 13: Now Run the application and see the output.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories