Donate

ASP.NET MVC Cascade Dropdown Using jQuery And Entity Framework

Team,

Here's an example of how to perform a cascading dropdown in ASP.NET MVC using jQuery and Entity Framework as the ORM. This example will use Microsoft's sample database called WideWorldImporters. So to start with, we need to create an ASP.NET MVC Project and add bootstrap and jQuery files through NuGet. Then add an ADO.NET Entity Data Model (Entity Framework) which maps to the WideWorldImporters database. Once done, add a new class called CountryStatesCitiesViewModel with an enumerable property called CountryList which contains country values that will bind to the country dropdownlist control in the UI.
public class CountryStatesCitiesViewModel
{
	public IEnumerable<SelectListItem> CountryList { get; set; }
}
Add a controller called Home with a default Index ActionResult method that retrieves country list from the database and store them to the model used for data binding of the dropdownlist control. I checked the WideWorldImporters db and found out that only the United States has corresponding state and cities. Next is add two methods that return a Json object. These methods query the database for the state provinces and it's corresponding cities. The parameters on both methods are the unique ID's and not their names.
public class HomeController : Controller
{
  private CountryStatesCitiesViewModel model;
  private WideWorldImportersEntities _context;

  // GET: Home
  public ActionResult Index()
  {
	 List<SelectListItem> itemCountries = new List<SelectListItem>();

	 _context = new WideWorldImportersEntities();
	 model = new CountryStatesCitiesViewModel();

	 var countries = (from ctr in _context.Countries select ctr).AsEnumerable().Select(x => new SelectListItem
	 {
		Value = x.CountryID.ToString(),
		Text = x.CountryName
	 }).Where(z => z.Text == "United States");

	 itemCountries.AddRange(countries);

	 model.CountryList = itemCountries;
	 return View(model);
  }

  public JsonResult GetStatesByID(int countryID)
  {
	 _context = new WideWorldImportersEntities();
	 return Json(_context.StateProvinces.Where(data => data.CountryID == countryID).Select(x => new { value = x.StateProvinceID, text = x.StateProvinceName })
				 , JsonRequestBehavior.AllowGet);
  }

  public JsonResult GetCitiesByID(int stateID)
  {
	 _context = new WideWorldImportersEntities();
	 return Json(_context.Cities.Where(data => data.StateProvinceID == stateID).Select(x => new { value = x.CityID, text = x.CityName })
				 , JsonRequestBehavior.AllowGet);
  }
}
The last part is to add an Index page with three dropdown controls designated for the country, state province and city. The country dropdown values were populated with values during Index method execution. The state dropdown will be populated with values when a specific country was chosen by the user and likewise the city dropdown will be populated with values if a selection happens from the state dropdown. The cascade effect was done using jQuery by calling the change function for the country and state dropdowns that is shown in the script section of the page.
@{
    ViewBag.Title = "Index";
}
@model CascadingDropdown.Models.CountryStatesCitiesViewModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
    <script type="text/javascript" src="~/scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#CountryID").change(function () {
                var selectedCountry = $(this).val();
                if (selectedCountry != "") {
                    $.ajax({
                        url: "/Home/GetStatesByID",
                        data: { countryID: selectedCountry },
                        success: function (result) {
                            if (result != undefined) {
                                $("#StateID").empty();
                                $("#StateID").append($("<option></option>").attr("value", "").text("-- Select State --"));
                                $.each(result, function (index, elem) {
                                    if (index == 0) {
                                        $("#StateID").append($("<option></option>")
                                            .attr("selected", "selected")
                                            .attr("value", elem.value)
                                            .text(elem.text));
                                    }
                                    else {
                                        $("#StateID").append($("<option></option>").attr("value", elem.value).text(elem.text));
                                    }
                                });
                                $("#StateID").change();
                            }
                        }
                    });
                }
            });

            $("#StateID").change(function () {
                var selectedState = $(this).val();
                if (selectedState != "") {
                    $.ajax({
                        url: "/Home/GetCitiesByID",
                        data: { stateID: selectedState },
                        success: function (result) {
                            if (result != undefined) {
                                $("#CityID").empty();
                                $("#CityID").append($("<option></option>").attr("value", "").text("-- Select City --"));
                                $.each(result, function (index, elem) {
                                    if (index == 0) {
                                        $("#CityID").append($("<option></option>")
                                            .attr("selected", "selected")
                                            .attr("value", elem.value)
                                            .text(elem.text));
                                    }
                                    else {
                                        $("#CityID").append($("<option></option>").attr("value", elem.value).text(elem.text));
                                    }
                                });
                            }
                        }
                    });
                }
                else {
                    $("#CityID").empty();
                    $("#CityID").append($("<option></option>").attr("value", "").text("-- Select City --"));
                }
            });

        });
    </script>
    <style type="text/css">
        .row{
            margin-bottom: 10px !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <br />
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-3">
                    Country:
                </div>
                <div class="col-md-9">
                    @Html.DropDownListFor(x => x.CountryList, new SelectList(Model.CountryList, "Value", "Text"),
                                      "-- Select Country --", new { id = "CountryID", @class = "form-control" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-3">
                    State:
                </div>
                <div class="col-md-9">
                    @Html.DropDownList("StateID", new List<SelectListItem>(), "-- Select State --", new { id = "StateID", @class = "form-control" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-3">
                    City:
                </div>
                <div class="col-md-9">
                    @Html.DropDownList("CityID", new List<SelectListItem>(), "-- Select City --", new { id = "CityID", @class = "form-control" })
                </div>
            </div>
        </div>
    </div>    
</body>
</html>
Output With Changes Done On States Dropdown
ASP.NET MVC Cascade Dropdown Using jQuery And Entity Framework
ASP.NET MVC Cascade Dropdown Using jQuery And Entity Framework

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input