In a Web Form, a DropDownList is common and time to time we need to provide the functionality of cascading between dropdownlists. Today in this article we will learn how to populate a dropdownlist and cascade between those dropdownlists.
How to populate a Dropdownlist in ASP.Net MVC
In this article we have a School database with the following 2 tables.
- StateMaster
- DistrictMaster
Step 1
Open Visual Studio then select File >> New >> Project then select ASP.Net MVC 4 Web Application.
Step 2
Select Internet Application then click OK.
Step 3
Select the Model folder then create a new Model class.
StudentModel.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcDemoApplication.Models
- {
- public class StudentModel
- {
- public IList<SelectListItem> StateNames { get; set; }
- public IList<SelectListItem> DistrictNames { get; set; }
- }
- }
Step 4
Create a .edmx file and connect with the database.
Step 5
Create a new Controller. In this article I create DropDownListController.cs.
DropDownListController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcDemoApplication.Models;
-
- namespace MvcDemoApplication.Controllers
- {
- public class DropDownListController : Controller
- {
-
-
- SchoolEntities schoolEntity = new SchoolEntities();
- public ActionResult Index()
- {
- List<SelectListItem> stateNames = new List<SelectListItem>();
- StudentModel stuModel=new StudentModel();
-
- List<StateMaster> states = schoolEntity.StateMasters.ToList();
- states.ForEach(x =>
- {
- stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });
- });
- stuModel.StateNames = stateNames;
- return View(stuModel);
- }
- }
- }
Index.cshtml
- @model MvcDemoApplication.Models.StudentModel
- @{
- ViewBag.Title = "Index";
- }
-
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
-
- <h2>Cascading Dropdownlist</h2>
- <table>
- <tr>
- <td>
- <label>State</label>
- </td>
- <td>
- @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});
- </td>
- </tr>
- </table>
Understand the Code
In Studentmodel we have the following 2 properties:
-
- public IList<SelectListItem> StateNames { get; set; }
-
- public IList<SelectListItem> DistrictNames { get; set; }
Here we are using the SelectListItem class, this class has the following 3 properties:
- Selected: This is a bool type to show in a dropdown (as selected) true or false by default.
- Text: This is a string type, for the dropdown text.
- Value: This is string type for the value of the dropdown
If you notice in the dropdownlist, we also need the same properties. For this reason we are using SelectListItem in a Ilist.
DropdownlistController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcDemoApplication.Models;
-
- namespace MvcDemoApplication.Controllers
- {
- public class DropDownListController : Controller
- {
-
-
- SchoolEntities schoolEntity = new SchoolEntities();
- public ActionResult Index()
- {
- List<SelectListItem> stateNames = new List<SelectListItem>();
- StudentModel stuModel=new StudentModel();
-
- List<StateMaster> states = schoolEntity.StateMasters.ToList();
- states.ForEach(x =>
- {
- stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });
- });
- stuModel.StateNames = stateNames;
- return View(stuModel);
- }
- }
- }
In the preceding code we create the SchoolEntities object, in this object all the related tables exist.
- SchoolEntities schoolEntity = new SchoolEntities();
-
- List<StateMaster> states = schoolEntity.StateMasters.ToList();
In the preceding line of code, all the related data of the StateMasters tables comes into the StateMaster list object.
- states.ForEach(x =>
- {
- stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });
- });
Now it is time to add entity data into the Text and value properties, the all collection will be stored into the stateNames object.
Index.cshtml
- @model MvcDemoApplication.Models.StudentModel
- @{
- ViewBag.Title = "Index";
- }
-
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
-
- <h2>Cascading Dropdownlist</h2>
- <table>
- <tr>
- <td>
- <label>State</label>
- </td>
- <td>
- @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});
- </td>
- </tr>
- </table>
The preceding code shows the model data in View. Now to understand how it works.
- @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});
Look at the preceding code, we used here, @Html helper classes for creating a DropDownList. In the DropDownListFor helper class we used 4 parameters.
- x=>x.StateNames: For getting the values of the collection from the entity.
- Model.StateNames: Collections of states.
- “—Select--”: Default value, when the dropdown list will be populated.
- new {@id=”ddlState”}: In this part we can define an id, class and name for the control.
How to do cascading between two dropdownlists.
DropdownlistController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcDemoApplication.Models;
-
- namespace MvcDemoApplication.Controllers
- {
- public class DropDownListController : Controller
- {
-
-
- SchoolEntities1 schoolEntity = new SchoolEntities1();
- public ActionResult Index()
- {
- List<SelectListItem> stateNames = new List<SelectListItem>();
- StudentModel stuModel=new StudentModel();
-
- List<StateMaster> states = schoolEntity.StateMasters.ToList();
- states.ForEach(x =>
- {
- stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });
- });
- stuModel.StateNames = stateNames;
- return View(stuModel);
- }
-
- [HttpPost]
- public ActionResult GetDistrict(string stateId)
- {
- int statId;
- List<SelectListItem> districtNames = new List<SelectListItem>();
- if (!string.IsNullOrEmpty(stateId))
- {
- statId = Convert.ToInt32(stateId);
- List<DistrictMaster> districts = schoolEntity.DistrictMasters.Where(x => x.StateId == statId).ToList();
- districts.ForEach(x =>
- {
- districtNames.Add(new SelectListItem { Text = x.DistrictName, Value = x.DistrictId.ToString() });
- });
- }
- return Json(districtNames, JsonRequestBehavior.AllowGet);
- }
-
- }
- }
Index.cshtml
- @model MvcDemoApplication.Models.StudentModel
- @{
- ViewBag.Title = "Index";
- }
-
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
-
- <h2>Cascading Dropdownlist</h2>
- <table>
- <tr>
- <td>
- <label>State</label>
- </td>
- <td>
- @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});
- </td>
- </tr>
- <tr>
- <td>
- <label>District</label>
- </td>
- <td id="District">
- @Html.DropDownListFor(x => x.DistrictNames, new List<SelectListItem>(), "--Select--", new { @id="ddlDistrict"});
- </td>
- </tr>
- </table>
-
- <script type="text/javascript">
- $(document).ready(function () {
- $('#ddlState').change(function () {
- $.ajax({
- type: "post",
- url: "/DropDownList/GetDistrict",
- data: { stateId: $('#ddlState').val() },
- datatype: "json",
- traditional: true,
- success: function (data) {
- var district = "<select id='ddlDistrict'>";
- district = district + '<option value="">--Select--</option>';
- for (var i = 0; i < data.length; i++)
- {
- district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
- }
- district = district + '</select>';
- $('#District').html(district);
- }
- });
- });
- });
- </script>
That's it. Press F5 and run your code. For any query please send your comments here.