Cascading Dropdownlist in ASP.Net MVC4 using AngularJS

In this article we are going to see the implementation of Cascading Dropdownlist 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 CascadingDropDownKOjs.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 CascadingDropDownKOjs.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 Dropdownlist,then Cities Dropdownlist will automatically populated.

csdang

Happy Coding!!!

You may also like...

  • kenny

    Nice tutorial, trying to achieve same using $resource instead of $http but on trying to save I’m getting null values for the country and state fields…

    –State of work–

    –Local govt–

  • MohanaKrishna G

    @Kenny It works fine with the $resource also.Check the following pointers in your code
    Whether you have given the reference of angular-resource.js file and check whether the angular $resource is injected in the angular module or not? and check whether you have given the query method as GET?

  • dj

    plz,give me in entity format.

  • Jack Frost

    What about selecting the previously selected value if the viewmodel is sent back after validation?

  • bujjibabu

    Hello I am trying to bind the values to the subcategory field but it’s not binding
    could you please help me to bind the values while selecting Category needs to filter and bind values to the Subcategory field.

  • Subodh

    This doesnt seem to be valid code:

    var cityList = City.GetCityList().Where(s => s.StateCode.ToLower() == code.ToLower());

  • Subodh

    My bad.. i jumped the gun there :)

    Although, i am trying to update this one to have all the states and city listed when the page is loaded and then filter the data as and when state is selected.

    Suggestions?