Cascading Drop-down list in ASP.Net MVC4 using AngularJS

In this article we are going to see the implementation of Cascading Drop-down list in ASP.Net MVC using AngularJS. First, create an ASP.Net MVC4 Internet Web application and add the following State.cs and City.cs classes under the Models folder of the application.

State.cs-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CasadingDrop_down.Models
{
    public class State
    {
        public string Code { get; set; }
        public string Name { get; set; }

        public static List<State> GetStateList()
        {
            return new List<State> { 
                new State{ Code="AP",Name="AndhraPradesh"},
                new State{ Code="KA",Name="Karnataka"},
                new State{ Code="MH",Name="Maharashtra"}
            };
        }
    }
}

City.cs-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CasadingDrop_down.Models
{
    public class City
    {
        public string StateCode { get; set; }
        public int CityId { get; set; }
        public string CityName { get; set; }

        public static List<City> GetCityList()
        {
            int id = 0;
            return new List<City> { 
                new City{ StateCode="AP",CityId=id++,CityName="Hyderabad"},
                new City{ StateCode="AP",CityId=id++,CityName="Vizag"},
                new City{ StateCode="AP",CityId=id++,CityName="Vijayawada"},
                new City{ StateCode="KA",CityId=id++,CityName="Bangalore"},
                new City{ StateCode="KA",CityId=id++,CityName="Mysore"},
                new City{ StateCode="MH",CityId=id++,CityName="Mumbai"},
                new City{ StateCode="MH",CityId=id++,CityName="Pune"}
            };
        }
    }
}

Add the following methods to the HomeController.cs file.

HomeController.cs-

        public JsonResult GetStates()
        {
            return this.Json(State.GetStateList(), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetCities(string code)
        {
            var cityList = City.GetCityList().Where(s =>
                           s.StateCode.ToLower() == code.ToLower());
            return this.Json(cityList);
        }

Now install the AngularJS Nuget package by running the following command in the Package Manger Console window.

“Install-Package angularjs”

You can find some JavaScript libraries with the name angular under the Scripts folder of the application.

Now add the following scripts section to the index.cshtml file.

index.cshtml-

@*Referencing the Angular library to the page*@
@Scripts.Render("~/Scripts/angular.min.js") 

<script type="text/javascript">
    //Defining a module
    var myApp = angular.module('myApp', []);
    //Defining a Controller
    myApp.controller('MainCtrl', ['$scope', '$http',
        function ($scope, $http) {
            //Defining the $http service for getting the states
            $http({
                method: 'GET',
                url: '/Home/GetStates'
            }).
            success(function (data) {
                $scope.states = data;
            });

            //Defining the $http service for getting cities
            $scope.GetCities = function () {
                if ($scope.state) {
                    $http({
                        method: 'POST',
                        url: '/Home/GetCities/',
                        data: JSON.stringify({ code: $scope.state })
                    }).
                    success(function (data) {
                        $scope.cities = data;
                    });
                }
                else {
                    $scope.cities = null;
                }
            }

        }]);
</script>

Also, add the following Html markup to the index.cshtml file

index.cshtml-

<div data-ng-app="myApp">
    <div data-ng-controller="MainCtrl">
        <p>
            <b>State:</b>
            <select data-ng-model="state" 
             data-ng-options="s.Code as s.Name for s in states" 
             data-ng-change="GetCities()">
                <option value="">--Select State--</option>
            </select>
        </p>
        <p>
            <b>City:</b>
            <select data-ng-model="city" data-ng-disabled="!cities"
                  data-ng-options="c.CityId as c.CityName for c in cities">
                <option value="">--Select City--</option>
            </select>
        </p>
    </div>
</div>

Now,Run the application by pressing Ctrl+F5. Select a State in the States Drop-down list,then Cities Drop-down list will automatically populated.

image1

Happy Coding!!!

You may also like...