-->

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

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. 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.
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

// 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;
});

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 here, about Factory here and about $http here.

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 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>
}

Step-8: Run Application.


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

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.