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.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 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
- // 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 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.
- 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;
- });
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
- public 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>
- }
0 comments:
Post a Comment