Thursday, 21 May 2015

How to implement Cascading DropDownList with AngularJS and ASP.NET MVC

Part 5 - How to implement Cascading DropDownList with AngularJS and ASP.NET MVC


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. 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 webpage 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. 
Here we will use AngularJS ng-change directive will allow us to monitor value changes on input elements and allows you to specify custom behavior in our AngularJS applications. Like here in this application, I have used ng-change in a Dropdown to monitor value changes and specify a function (custom behavior), which will fire when the value of the dropdown has been changed.

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. 
In this example, I have used two tables as below


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 

  1. // Fetch Country
  2. public JsonResult GetCountries()
  3. {
  4. List<Country> allCountry = new List<Country>();
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
  8. }
  9. return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  10. }

STEP-4: ADD A 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 

  1. // Fetch State by Country ID
  2. public JsonResult GetStates(int countryID)
  3. {
  4. List<State> allState = new List<State>();
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. allState = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
  8. }
  9. return new JsonResult { Data = allState, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  10. }

STEP-5: ADD A NEW JS FILE FOR ADD A NEW ANGULARJS CONTROLLER AND A FACTORY

Go to Solution Explorer > Right Click on folder (where you want to saved 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. 

  1. angular.module('MyApp') // extending from previously created angularJS module in the First part
  2. .controller('Part5Controller', function ($scope, LocationService) {
  3. // expained about controller in Part2 // Here LocationService (Service) Injected
  4.  
  5. $scope.CountryID = null;
  6. $scope.StateID = null;
  7. $scope.CountryList = null;
  8. $scope.StateList = null;
  9.  
  10. $scope.StateTextToShow = "Select State";
  11. $scope.Result = "";
  12.  
  13. // Populate Country
  14. LocationService.GetCountry().then(function (d) {
  15. $scope.CountryList = d.data;
  16. }, function (error) {
  17. alert('Error!');
  18. });
  19. // Function For Populate State // This function we will call after select change country
  20. $scope.GetState = function () {
  21. $scope.StateID = null; // Clear Selected State if any
  22. $scope.StateList = null; // Clear previously loaded state list
  23. $scope.StateTextToShow = "Please Wait..."; // this will show until load states from database
  24.  
  25. //Load State
  26. LocationService.GetState($scope.CountryID).then(function (d) {
  27. $scope.StateList = d.data;
  28. $scope.StateTextToShow = "Select State";
  29. }, function (error) {
  30. alert('Error!');
  31. });
  32.  
  33. }
  34. // Function for show result
  35. $scope.ShowResult = function () {
  36. $scope.Result = "Selected Country ID : " + $scope.CountryID + " State ID : " + $scope.StateID;
  37. }
  38.  
  39. })
  40. .factory('LocationService', function ($http) { // explained about factory in Part2
  41. var fac = {};
  42. fac.GetCountry = function () {
  43. return $http.get('/Data/GetCountries')
  44. }
  45. fac.GetState = function (countryID) {
  46. return $http.get('/Data/GetStates?countryID='+countryID)
  47. }
  48. return fac;
  49. });

Here I have created an angular controller named "Part5Controller" and a Factory named "LocationService" with $http injected service. I have explained a little about AngularJS controller, about Factory  and about $http 

STEP-6: ADD NEW ACTION INTO YOUR CONTROLLER (HERE IN THE HOMECONTROLLER) FOR GET THE VIEW FOR IMPLEMENT CASCADE DROPDOWNLIST.

Here I have added "Part5" Action into "Home" Controller. Please write this following code 

  1. public ActionResult Part5() // Implement Cascade dropdownlist
  2. {
  3. return View();
  4. }

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 
  1. @{
  2. ViewBag.Title = "Part5";
  3. }
  4.  
  5. <h2>Part5 - Cascade Dropdown using AngularJS and MVC4</h2>
  6.  
  7. <div ng-controller="Part5Controller">
  8. Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
  9. <option value="">Select Country</option>
  10. </select>
  11. State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
  12. <option value="">{{StateTextToShow}}</option>
  13. </select>
  14. <input type="button" value="Get Selected Values" ng-click="ShowResult()"/>
  15. <div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3">
  16. {{Result}}
  17. </div>
  18. </div>
  19.  
  20. @section scripts{
  21. <script src="~/Scripts/AngularController/Part5Controller.js"></script>
  22. }

STEP-8: RUN APPLICATION.

Related Posts:

0 comments: