In this article I will explain with an example, how to implement cascading i.e. dependent DropDownLists using
AngularJS in ASP.Net MVC.
Database
I have made use of the following three tables Countries, States and Cities with the schema as follow.
Countries Table
States Table
Cities Table
Note: You can download the database table SQL by clicking the download link below.
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the database using
Entity Framework.
Following is the Entity Data Models of the three Tables i.e. Countries, States and Cities which will be used later in this project.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method is executed when the call is made from
AngularJS client.
It accepts
type and
value as parameter and based on the
type i.e. Country or State, the records of States or Cities are fetched from the
SQL Server database and returned to View as JSON object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod(string type, int value)
{
List<SelectListItem> items = new List<SelectListItem>();
CascadingEntities entities = new CascadingEntities();
switch (type)
{
default:
foreach (var country in entities.Countries)
{
items.Add(new SelectListItem { Text = country.CountryName, Value = country.CountryId.ToString() });
}
break;
case "CountryId":
var states = (from state in entities.States
where state.CountryId == value
select state).ToList();
foreach (var state in states)
{
items.Add(new SelectListItem { Text = state.StateName, Value = state.StateId.ToString() });
}
break;
case"StateId":
var cities = (from city in entities.Cities
where city.StateId == value
select city).ToList();
foreach (var city in cities)
{
items.Add(new SelectListItem { Text = city.CityName, Value = city.CityId.ToString() });
}
break;
}
return Json(items);
}
}
View
Inside the View, the following script file is inherited.
1. angular.min.js
The HTML of the View consists of:
DIV – For applying
ng-app and
ng-controller AngularJS directives.
DropDownList – For displaying Country, State and City names.
The first two HTML SELECT elements (DropDownList) have been assigned with an
AngularJS ng-model directive.
The first option element of each HTML SELECT elements (DropDownList) is used to set the Default text.
The second option element of each HTML SELECT elements (DropDownList) has been assigned with the following
AngularJS directive.
ng-repeat – For repeating the element based on the length of the collection.
The
LoadDropDown function is applied to first two SELECT elements (DropDownList) using
AngularJS ng-change directive.
Inside the
AngularJS Controller, the
LoadDropDown function is called twice for populating DropDownLists for State and City.
Then, inside the LoadDropDown function, a switch and case statement is executed and Default Labels are set.
The
$http service is used to make an
AJAX call to the Controller’s Action method.
The $http service has following properties and event handlers.
Properties
1. method – The method type of HTTP Request i.e. GET or POST. Here it is set to POST.
2. url – URL of the Controller’s Action method.
3. datatype - The format of the data i.e. XML or JSON. Here it is set as JSON.
4. data – The parameters to be sent to the Controller's Action method.
5. headers - List of headers to be specified for the HTTP Request.
Event Handlers
1. success – This event handler is triggered once the
AJAX call is successfully executed.
2. error – This event handler is triggered when the
AJAX call encounters an error.
The response from the
AJAX call is received in JSON format inside the
Success event handler of the
$http service and again a
switch and
case statement is executed and Default Labels are set.
Finally, the DropDownLists are populated with their respective data.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.LoadDropDown = function (type, value) {
switch (type) {
default:
$scope.SelectedCountryId = 0;
$scope.CountryDefaultLabel = "Loading.....";
$scope.Countries = null;
break;
case "CountryId":
$scope.SelectedStateId = 0;
$scope.StateDefaultLabel = "Loading.....";
$scope.CityDefaultLabel = "";
$scope.States = null;
$scope.Cities = null;
break;
case "StateId":
$scope.SelectedCityId = 0;
$scope.CityDefaultLabel = "Loading.....";
$scope.Cities = null;
break;
}
$http({
method: "POST",
url: "/Home/AjaxMethod",
dataType: 'json',
data: '{type: "' + type + '", value: ' + value + '}',
headers: { "Content-Type": "application/json" }
}).success(function (data, status) {
switch (type) {
default:
$scope.CountryDefaultLabel = "Select Country";
$scope.Countries = data;
break;
case "CountryId":
$scope.StateDefaultLabel = "";
if (data.length > 0) {
$scope.StateDefaultLabel = "Select State";
$scope.States = data;
}
break;
case "StateId":
$scope.CityDefaultLabel = "";
if (data.length > 0) {
$scope.Cities = data;
$scope.CityDefaultLabel = "Select City";
}
break;
}
}).error(function (data, status) {
$window.alert(data.Message);
});
};
$scope.LoadDropDown('', 0);
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Country:</td>
<td>
<select name="Country" ng-model="SelectedCountryId" ng-change="LoadDropDown('CountryId',SelectedCountryId)">
<option value="0">{{CountryDefaultLabel}}</option>
<option ng-repeat="item in Countries" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>State:</td>
<td>
<select name="State" ng-model="SelectedStateId" ng-change="LoadDropDown('StateId',SelectedStateId)">
<option value="0">{{StateDefaultLabel}}</option>
<option ng-repeat="item in States" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>City:</td>
<td>
<select name="City">
<option value="0">{{CityDefaultLabel}}</option>
<option ng-repeat="item in Cities" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads