How to load cascading dropdown in asp.net MVC?


I am working on asp.net MVC web application, I want to fetch Second dropdown list based on value of first dropdown list, I know we can do it with Ajax, but I am not able to fetch results

How can achieve it, can anyone explain it with example, thanks

 


Asked by:- jaiprakash
2
: 4667 At:- 8/24/2017 7:48:52 AM
C# ASP-NET Cascading-dropdown-list







2 Answers
profileImage Answered by:- jaya

Here is the example with the steps for create cascading dropdown list using MVC C# and jquery

  • ·Add class to Models folder (District.cs)
  •  Add controller to Controllers folder (CascadingDropdownController

Class  District.cs should look like this.

public class District
    {
        public int DistrictID { get; set; }
        public string DistrictName { get; set; }
        public int ProvinceID { get; set; }
    }

Create a Controller (CascadingDropdownController), which is used to handle request and return back the list based on first dropdown list selected item ID

public class CascadingDropdownController : Controller
    {
        // GET: CascadingDropdown
        public ActionResult casDropDown()
        {
            List<SelectListItem> lst =
                new List<SelectListItem>() 
            {
                new SelectListItem { Value="1",Text="Province 1" },
                new SelectListItem{Value="2",Text="Province 2"},    
                new SelectListItem{Value="3",Text="Province 3"},
                new SelectListItem{Value="4",Text="Provice 4"}
            };
            
            ViewBag.Province = lst;

            return View();
        }

        [HttpPost]
        public JsonResult getDistricts(int provinceid)
        {
            List<District> dist = new List<District>();
            District[] DistArrary = { new District { DistrictID = 1, DistrictName = "District 1", ProvinceID = 1 },                                   
                                     new District { DistrictID=3, DistrictName="District 2",ProvinceID=1 },
                                     new District { DistrictID=4, DistrictName="District 3",ProvinceID=2 },
                                     new District { DistrictID=5, DistrictName="District 4",ProvinceID=3 },
                                     new District { DistrictID=6, DistrictName="District 5",ProvinceID=3 },
                                     new District { DistrictID=7, DistrictName="District 6",ProvinceID=3 },
                                     new District { DistrictID=8, DistrictName="District 7",ProvinceID=4 },
                                     new District { DistrictID=9, DistrictName="District 8",ProvinceID=4 },
                                     new District { DistrictID=10, DistrictName="District 9",ProvinceID=4 },
                                     new District { DistrictID=2, DistrictName="District 10",ProvinceID=2 },
                                     new District { DistrictID=11, DistrictName="District 11",ProvinceID=1 }};

            District[] selDists = DistArrary.Where(p => p.ProvinceID == provinceid).ToArray();

            return Json(selDists, JsonRequestBehavior.AllowGet);
        }

    }

Now let's create front end for it, Add a View, with following code

<h2>Cascading Dropdown</h2>
@using(Html.BeginForm())
{
    <hr />
  <div class="form-horizontal">
      <div class="form-group">
          <label class="col-md-2 control-label">Province</label>
          <div class="col-md-5">
             @Html.DropDownList("Province", null, htmlAttributes: new { @class = "form-control" })
          </div>
      </div>
      <div class="form-group">
          <label class="col-md-2 control-label">District</label>
          <div class="col-md-4">
              <select id="District" name="District" class="form-control"></select>
          </div>
      </div>
  </div>    
}

<script>
    $(function () {
       //Invoke jQuery function of First DDL change
        $('#Province').change(function () {
           //Get ID of selected Province
            var provinceid = $(this).val();
           // send selected ID to controller using Ajax
            $.ajax({
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                url: "getDistricts", // URL to fetch second ddl
                data: "{provinceid:'" + provinceid + "'}",
                success: function (data) {   
                   //append the data in second dropdown by creating html using jquery                
                    $('#District').empty();
                    $('#District').append('<option selected="selected" value="">Select District</option>')
                    $.each(data, function (i, d) {
                        $('#District').append('<option value=' + d.DistrictID + '>' + d.DistrictName + '</option>');
                    });

                },
                failure: function (data) {
                    alert('error occured');
                }

            });
        });
    });
</script>

Explanation

We have created two action method in the C# controller one is to load default select list(First select List, i.e casDropDown), and second method is to get List based on ID of selected Item of first DDL.

In the above code, we have implemented a jQuery function which will be called on Changing first dropdown list value,i.e "Province", on change of it, we are selecting it's ID and then sending it to C# controller Method(getDistricts(int provinceid)) using jQuery Ajax.

Sending ID of first DDL, we are getting list of second dropdown list based on ID of the selected item.

After getting the JSON Result as List of districts we are appending it into HTML(dynamically) using jQuery, hence showing the data based on first dropdown list selected item.

2
At:- 8/24/2017 3:27:56 PM Updated at:- 8/24/2017 3:28:21 PM
good answer with proper details 1
By : jaiprakash - at :- 9/15/2017 3:46:42 PM
that's what I was looking for :) 1
By : Vinnu - at :- 9/21/2017 2:33:06 PM


profileImage Answered by:- vikas_jk

Here is the another solution, just for reference as this question is old, but will help to understand cascading dropdown list easily in MVC using jQuery

First your let's go to your controller, in Controller, GetChildItems is the action method which is called from jquery ajax request to get the desired child dropdownlist items based on the selection of parent

public ActionResult GetChildItems(string baseItem)
{
    if (baseItem == "Year")
    {
        List<SelectListItem> lstChildItems = new List<SelectListItem>();
        lstChildItems.Add(new SelectListItem { Value = "Jan", Text = "Jan" });
        lstChildItems.Add(new SelectListItem { Value = "Feb", Text = "Feb" });
        lstChildItems.Add(new SelectListItem { Value = "March", Text = "March" });
        lstChildItems.Add(new SelectListItem { Value = "April", Text = "April" });
        lstChildItems.Add(new SelectListItem { Value = "May", Text = "May" });
        lstChildItems.Add(new SelectListItem { Value = "June", Text = "June" });
        return Json(lstChildItems, JsonRequestBehavior.AllowGet);
    }
    else
    {
        List<SelectListItem> lstChildItems = new List<SelectListItem>();
        lstChildItems.Add(new SelectListItem { Value = "Sunday", Text = "Sunday" });
        lstChildItems.Add(new SelectListItem { Value = "Monday", Text = "Monday" });
        lstChildItems.Add(new SelectListItem { Value = "Tuesday", Text = "Tuesday" });
        lstChildItems.Add(new SelectListItem { Value = "Wednesday", Text = "Wednesday" });
        lstChildItems.Add(new SelectListItem { Value = "Thrusday", Text = "Thrusday" });
        lstChildItems.Add(new SelectListItem { Value = "Friday", Text = "Friday" });
        lstChildItems.Add(new SelectListItem { Value = "Saturday", Text = "Saturday" });
        return Json(lstChildItems, JsonRequestBehavior.AllowGet);
 
    }
}

BaseItems is the property of the model which contains the list of items to be binded to parent dropdownlist.
It makes ajax request on change event of parent dropdownlist

In the View your code can be

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 
@Html.DropDownListFor(
    x => x.BaseItem,
    new SelectList(Model.BaseItems, "Value", "Text"),
    "-- select base --"
)
 
@Html.DropDownListFor(
    x => x.ChildItem,
    Enumerable.Empty<SelectListItem>(),
    "-- select child --"
)
 
<script type="text/javascript">
    $('#BaseItem').change(function () {
        var selectedBaseItem = $(this).val();
        if (selectedBaseItem != null && selectedBaseItem != '') {
            $.getJSON('@Url.Action("GetChildItems")', { baseItem: selectedBaseItem }, function (childItems) {
                var childDDItems = $('#ChildItem');
                childDDItems.empty();
                $.each(childItems, function (index, item) {
                    childDDItems.append($('<option/>', {
                        value: item.Value,
                        text: item.Text
                    }));
                });
            });
        }
    });
</script>

Model:

public class MyViewModel
{
    public int? BaseItem { get; set; }
    public int? ChildItem { get; set; }
 
    public IEnumerable<SelectListItem> BaseItems
    {
        get
        {
 
            List<SelectListItem> lstBaseItems = new List<SelectListItem>();
            lstBaseItems.Add(new SelectListItem
            {
                Value = "Year",
                Text = "Year"
            });
            lstBaseItems.Add(new SelectListItem
            {
                Value = "Week",
                Text = "Week"
            });
            return lstBaseItems;
 
        }
    }
}

That's it, You are done, based on First dropdown if we select "Year", second dropdown will have "Jan","Feb"....etc in it , if we select "Week", second dropdown will have "Sunday","Monday"...etc as data.

cascading-drop-down-list-in-mvc-min.gif

1
At:- 3/21/2018 11:55:24 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use