Introduction
In this post, I would like to explain Part 5 - How to implement Cascading DropDownList with AngularJS and ASP.NET MVC.This is our 5th Post about AngularJS. Here I have explained a little about AngularJS and What we will learn in this section part by part.
Sometimes we need to display DropDownLists in our web page such that values in one DropDownList are dependent on the value selected in another DropDownList. The most common example of such a functionality is countries and states DropDownLists where based on a selected country you need to populate the states, DropDownList. In this article, I would like to explain how to implement Cascading DropDownList with AngularJS and ASP.NET MVC.
Steps :
Step-1: Create 2 table into the database (here Country and State).
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.Step-2: Update Entity Data Model.
Go to Solution Explorer > Open your Entity Data Model (here "MyModel.edmx") > Right Click On Blank area for Get Context Menu > Update Model From Database... > A popup window will come (Entity Data Model Wizard) > Select Tables > Finish.Step-3: Add new action into your controller (here in the Data Controller) for Fetch Data (List of Data / Array of data) and return as JsonResult from Database.
Here I have added "GetCountries" Action into "DataController". Please write this following code// Fetch Country public JsonResult GetCountries() { List<Country> allCountry = new List<Country>(); using (MyDatabaseEntities dc = new MyDatabaseEntities()) { allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList(); } return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
Step-4: Add an another new action into your controller (here in the Data Controller) for Fetch Data (List of Data / Array of data) and return as JsonResult from Database.
Here I have added "GetStates" Action into "DataController". Please write this following code// Fetch State by Country ID public JsonResult GetStates(int countryID) { List<State> allState = new List<State>(); using (MyDatabaseEntities dc = new MyDatabaseEntities()) { allState = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList(); } return new JsonResult { Data = allState, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
Step-5: Add a new js File for add a new AngularJS controller and a Factory
Go to Solution Explorer > Right Click on the folder (where you want to save your AngularJS controller files, here I have created a folder named "AngularController" under Scripts Folder) > Add > Select Javascript file > Enter name > Add.Write following code in this file.
angular.module('MyApp') // extending from previously created angularJS module in the First part .controller('Part5Controller', function ($scope, LocationService) { // expained about controller in Part2 // Here LocationService (Service) Injected $scope.CountryID = null; $scope.StateID = null; $scope.CountryList = null; $scope.StateList = null; $scope.StateTextToShow = "Select State"; $scope.Result = ""; // Populate Country LocationService.GetCountry().then(function (d) { $scope.CountryList = d.data; }, function (error) { alert('Error!'); }); // Function For Populate State // This function we will call after select change country $scope.GetState = function () { $scope.StateID = null; // Clear Selected State if any $scope.StateList = null; // Clear previously loaded state list $scope.StateTextToShow = "Please Wait..."; // this will show until load states from database //Load State LocationService.GetState($scope.CountryID).then(function (d) { $scope.StateList = d.data; $scope.StateTextToShow = "Select State"; }, function (error) { alert('Error!'); }); } // Function for show result $scope.ShowResult = function () { $scope.Result = "Selected Country ID : " + $scope.CountryID + " State ID : " + $scope.StateID; } }) .factory('LocationService', function ($http) { // explained about factory in Part2 var fac = {}; fac.GetCountry = function () { return $http.get('/Data/GetCountries') } fac.GetState = function (countryID) { return $http.get('/Data/GetStates?countryID='+countryID) } return fac; });
Step-6: Add new action into your controller (here in the HomeController) for Get the View for implement cascade drop-down list.
Here I have added "Part5" Action into "Home" Controller. Please write this following codepublic ActionResult Part5() // Implement Cascade dropdownlist { return View(); }
Step-7: Add view for the Action & design.
Right Click on Action Method (here right click on Part5 action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.Complete View
@{ ViewBag.Title = "Part5"; } <h2>Part5 - Cascade Dropdown using AngularJS and MVC4</h2> <div ng-controller="Part5Controller"> Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()"> <option value="">Select Country</option> </select> State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList"> <option value="">{{StateTextToShow}}</option> </select> <input type="button" value="Get Selected Values" ng-click="ShowResult()"/> <div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3"> {{Result}} </div> </div> @section scripts{ <script src="~/Scripts/AngularController/Part5Controller.js"></script> }