Cascading DropDownList in ASP.NET MVC

In this article, you will learn how to create a cascading DropDownList in ASP.NET MVC. I will show you the procedure step-by-step. So, let's begin.

Case Study: I will create two DDLs (State and District). The first DDL will let you pick a state and when you a pick state, it will make a parameterized JSON call using jQuery that will return a matching set of districts that will be populated to the second DDL. I will also show how to use proper validations with each control. Here is the animated screen that we are going to create:

Now, let's see the procedure.

Step 1

At the very first, we need a model class that defines the properties for storing data.

  1. public class ApplicationForm  
  2. {  
  3.     public string Name { getset; }  
  4.     public string State { getset; }  
  5.     public string District { getset; }  
  6. }  

Step 2

Now, we need an initial controller that will return an Index view by a packing list of states in ViewBag.StateName.

  1. public ActionResult Index()  
  2. {  
  3.     List<SelectListItem> state = new List<SelectListItem>();  
  4.     state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });  
  5.     state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });  
  6.     ViewBag.StateName = new SelectList(state, "Value""Text");  
  7.     return View();  
  8. } 

In the above controller we have a List<SelectListItem> containing states attached to ViewBag.StateName. We could get a list of states from the database using a LINQ query or something and pack it into ViewBag.StateName. Well let's go with in-memory data.

Step 3

Once we have a controller we can add its view and start creating a Razor form.

  1. @Html.ValidationSummary("Please correct the errors and try again.")  
  2. @using (Html.BeginForm())  
  3. {  
  4.     <fieldset>  
  5.         <legend>DropDownList</legend>  
  6.         @Html.Label("Name")  
  7.         @Html.TextBox("Name")  
  8.         @Html.ValidationMessage("Name""*")  
  9.         @Html.Label("State")  
  10.         @Html.DropDownList("State", ViewBag.StateName as SelectList, "Select a State"new { id = "State" })  
  11.         @Html.ValidationMessage("State""*")  
  12.         @Html.Label("District")  
  13.         <select id="District" name="District"></select>  
  14.         @Html.ValidationMessage("District""*")  
  15.         <p>  
  16.             <input type="submit" value="Create" id="SubmitId" />  
  17.         </p>  
  18.     </fieldset>  
  19. } 

You can see I have added proper labels and validation fields with each input control (two DropDownLists and one TextBox) and also a validation summery at the top. Notice, I have used <select id="District"….> which is HTML instead of a Razor helper; this is because when we make a JSON call using jQuery we will return HTML markup of the pre-populated option tag. Now, let's add jQuery code in the above view page.

Step 4

Here is the jQuery code making a JSON call to the DDL named controller's DistrictList method with a parameter (which is the selected state name). The DistrictList method will return JSON data. With the returned JSON data we are building <option> tag HTML markup and attaching this HTML markup to "District" which is a DOM control.

  1. @Scripts.Render("~/bundles/jquery")  
  2. <script type="text/jscript">  
  3.     $(function () {  
  4.         $('#State').change(function () {  
  5.             $.getJSON('/DDL/DistrictList/' + $('#State').val(), function (data) {  
  6.                 var items = '<option>Select a District</option>';  
  7.                 $.each(data, function (i, district) {  
  8.                     items += "<option value='" + district.Value + "'>" + district.Text + "</option>";  
  9.                 });  
  10.                 $('#District').html(items);  
  11.             });  
  12.         });  
  13.     });  
  14. </script> 

Please make sure you are using jQuery library references before the <script> tag.

Step 5

In the above jQuery code we are making a JSON call to DDL named controller's DistrictList method with a parameter. Here is the DistrictList method code that will return JSON data.

  1. public JsonResult DistrictList(string Id)  
  2. {  
  3.     var district = from s in District.GetDistrict()  
  4.                     where s.StateName == Id  
  5.                     select s;  
  6.     return Json(new SelectList(district.ToArray(), "StateName""DistrictName"), JsonRequestBehavior.AllowGet);  
  7. } 

Please note, the DistrictList method will accept an "Id" (it should be "Id" always) parameter of string type sent by the jQuery JSON call. Inside the method, I am using an "Id" parameter in the LINQ query to get a list of matching districts and conceptually, in the list of district data there should be a state field. Also note, in the LINQ query I am making a method called District.GetDistrict().

Step 6

In the above District.GetDistrict() method call, District is a model that has a GetDistrict() method. And I am using the GetDistrict() method in the LINQ query, so this method should be of type IQueryable. Here is the model code.

  1. public class District  
  2. {  
  3.     public string StateName { getset; }  
  4.     public string DistrictName { getset; }  
  5.     public static IQueryable<District> GetDistrict()  
  6.     {  
  7.         return new List<District>  
  8.         {  
  9.             new District { StateName = "Bihar", DistrictName = "Motihari" },  
  10.             new District { StateName = "Bihar", DistrictName = "Muzaffarpur" },  
  11.             new District { StateName = "Bihar", DistrictName = "Patna" },  
  12.             new District { StateName = "Jharkhand", DistrictName = "Bokaro" },  
  13.             new District { StateName = "Jharkhand", DistrictName = "Ranchi" },  
  14.         }.AsQueryable();  
  15.     }  
  16. } 

Step 7 

You can run the application here because the cascading dropdownlist is ready now. I will do some validation when the user clicks the submit button. So, I will add another action result of the POST version.

  1. [HttpPost]  
  2. public ActionResult Index(ApplicationForm formdata)  
  3. {  
  4.     if (formdata.Name == null)  
  5.     {  
  6.         ModelState.AddModelError("Name""Name is required field.");  
  7.     }  
  8.     if (formdata.State == null)  
  9.     {  
  10.         ModelState.AddModelError("State""State is required field.");  
  11.     }  
  12.     if (formdata.District == null)  
  13.     {  
  14.         ModelState.AddModelError("District""District is required field.");  
  15.     }  
  16.     if (!ModelState.IsValid)  
  17.     {  
  18.         //Populate the list again  
  19.         List<SelectListItem> state = new List<SelectListItem>();  
  20.         state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });  
  21.         state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });  
  22.         ViewBag.StateName = new SelectList(state, "Value""Text");  
  23.         return View("Index");  
  24.     }  
  25.     //TODO: Database Insertion  
  26.     return RedirectToAction("Index""Home");  
  27. }

And, this action result will accept ApplicationForm model data and based on posted data will do validations. If a validation error occurs, the action method calls the AddModelError method to add the error to the associated ModelState object. The AddModelError method accepts the name of the associated property and the error message to display. After the action method executes the validation rules, it uses the IsValid property of the ModelStateDictionary collection to determine whether the resulting data complies with the model.

So, this is all. If you wish to see the complete code, use the links given below.

Model: ApplicationForm.cs | Controller: DDLController.cs | View: Index.cshtml

Hope this helps.


Similar Articles