Cascading DropDownList in MVC 5 Using jQuery with SQL

Updated : Nov 02, 2019 in Articles

Cascading DropDownList in MVC Using jQuery with Ajax

In this article, we will learn about cascading DropDownList in MVC 5 Using jQuery step by step, we will implement by using Ajax Server Database

Requirement

We have categories like mobiles, TVs, laptops…, in my dropdownList we want to display categories wise subcategories in another Cascading DropDownList like (apple, Samsung, Lenovo, Mi Tv…)

Before going to implementing the cascading dropdown list Download the jquery CDN 1.10.2.js version.

Steps for implementation Cascading DropDownList

  1. Creating a database
  2. Add Ado.net data entity model to project
  3. implementing a controller for Cascading DropDownList
  4. writing Ajax script for binding subcategories to Cascading DropDownList

Step 1: Creating a Database

open your SQL server create a database, add two tables name like category and subcategories and dump some dummy data in tables execute the given below SQL Query

create table [dbo].[category] (
categoryId int,
categoryName  [nvarchar](30) NULL
)

insert into [category](categoryId,categoryName)values(1,'Mobiles');
insert into [category](categoryId,categoryName)values(2,'TVs');
insert into [category](categoryId,categoryName)values(3,'Laptops');

create Table [dbo].[subcategories](
subcatId int,
Fk_CatId int,
Subcategoryname  [nvarchar](30) NULL
)

insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(1,1,'Iphone');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(2,1,'Redmi');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(3,1,'samsung');

insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(4,2,'LG Tvs');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(5,2,'Sony Bravia Full HD');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(6,2,'TCL P6 Ultra HD LED');

insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(7,3,'HP');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(8,3,'Dell');
insert into [subcategories](subcatId,Fk_CatId,Subcategoryname)values(9,3,'iBall ');

Step 2: Add Ado.net data entity model to project

Go to your project Add Ado.net data entity model

Cascading DropDownList in MVC 5
implementing DropDownList in MVC 5 Using jQuery

Step 3: implementing a controller for Cascading DropDownList

right-click on your controller folder Add controller name like CascadeDropDownLists

first, we will display the all categories name in the dropdown list for this we will implement the index action method

In the index action method, we will get all categories and put into the viewBag this viewBag we use at the view level, follow the given below code

 TestDBEntities context = new TestDBEntities();
  // GET: CascadeDropDownLists
  public ActionResult Index()
  {
    ViewBag.categories = context.categories1.ToList();
    return View();
  }

Create a view for the index action method and add Give below code

@model SavingItemsState.Entity.TestDBEntities
    @{
        ViewBag.Title = "Index";
    }
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <h2>Index</h2>
      
   <p>
        @Html.DropDownListFor(Model => Model.categories1, new SelectList(ViewBag.categories as System.Collections.IEnumerable, "categoryId", "categoryName"),

                "Select a categorie", new { id = "dd_Country" })
    </p>

Run your application

Cascading DropDownList in MVC 5 Using jQuery
Cascading DropDownList in MVC Using jQuery

next step we will bind category wise subcategories in another Cascading DropDownList

  public class CascadeDropDownListsController : Controller
    {
        TestDBEntities context = new TestDBEntities();
        // GET: CascadeDropDownLists
        public ActionResult Index()
        {
            ViewBag.categories = context.categories1.ToList();
            return View();
        }
        private IList<subcategory> Getsubcategories(int categoryId)
        {
            return context.subcategories.Where(m => m.Fk_CatId == categoryId).ToList();
        }
        public JsonResult LoadSubCatBycategoryId(int categoryId)
        {
            var subcategoriesList = Getsubcategories(categoryId);
            var subcategoriesData = subcategoriesList.Select(m => new SelectListItem()
            {
                Text = m.Subcategoryname.ToString(),
                Value = m.subcatId.ToString(),
            });
            return Json(subcategoriesData, JsonRequestBehavior.AllowGet);
        }
    }

here we will use ajax request for calling subcategories based on categories for this we will implement the Ajax script. following given below script code

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $("#dd_Country").change(function () {
                var categoryId = $(this).val();
                $.getJSON("../CascadeDropDownLists/LoadSubCatBycategoryId", { categoryId: categoryId },
                    function (classesData) {
                        var select = $("#ddState");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select a subcategorie"
                        }));
                        $.each(classesData, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
            });
        });
    </script>

create subcategory Cascading DropDownList in the same view page(index view page)

 <p>
        @Html.DropDownListFor(Model => Model.subcategories, new SelectList(Enumerable.Empty<SelectListItem>(), "subcatId", "Subcategoryname"),
                "Select a subcategorie", new { id = "ddState" })
    </p>

Run your Application thanks…

OutPut:

Cascading DropDownList in MVC 5 Using jQuery with SQL
Cascading DropDownList in MVC 5 Using jQuery with SQL

Summary

In the above article, we will learn about cascading DropDownList in MVC 5 Using jQuery with Ajax with Database next article we will learn the same concept using Ado.Net

you will also see the Autocomplete textbox in MVC using jquery.

Follow the link for Interview Questions on Asp.net MVC.

Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x