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
: 179 At:- 8/24/2017 7:48:52 AM
C# ASP-NET Cascading-dropdown-list






1 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





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