Wednesday, June 1, 2016

Populate dropdownlist based on another dropdownlist using AngularJs in MVC

In this article I am going to explain how to populate dropdownlist based on another dropdownlist using AngularJs in MVC

Populate dropdownlist based on another dropdownlist using AngularJs in MVC




Description:
I want to fill state dropdownlist based on Country dropdown selection and city dropdown based on state dropdown selection. For example if I select Country India, all Indian state be shown in state dropdown and similarly select state (Himachal Pradesh) city dropdown will be populate with all himachal’s cities stored in database.

Implementation:

Below given are the classes in Model:-
Country.cs
    public partial class Tb_Country
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
    }
State.cs
    public partial class Tb_State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
        public Nullable<int> CountryId_Fk { get; set; }
    }
City.cs
   public partial class Tb_City
    {
        public int Id { get; set; }
        public string CityName { get; set; }
        public Nullable<int> StateId_Fk { get; set; }
    }

Add controller
Now add a controller to project. Here I have added empty controller. Create Json action to fetch the data from database. Write the code as given below:

Controller Code(IndexController.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;

namespace MVC_Project.Controllers
{
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        DemoEntities1 db = new DemoEntities1();
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetCountry()
        {
            var country = db.Tb_Country.Select(c=> new{c.Id,c.CountryName}).ToList();
            return Json(country, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult Getstate(int CountryId_Fk)
        {
            var state = db.Tb_State.Where(s => s.CountryId_Fk == CountryId_Fk).Select(s => new { s.Id, s.StateName }).OrderBy(s=>s.StateName).ToList();
            return Json(state);
        }
        [HttpPost]
        public JsonResult GetCity(int StateId_Fk)
        {
            var city = db.Tb_City.Where(c => c.StateId_Fk == StateId_Fk).Select(c => new { c.Id, c.CityName }).OrderBy(c=>c.CityName).ToList();
            return Json(city);
        }
    }
}

Add View
Add a view for Index action. Add the reference of AngularJs to view. Below is the code of view.

View (Index.cshtml):

@{
    ViewBag.Title = "Cascading dropdown AngulatJs example";
} 
<fieldset style="width: 25%;">
    <legend>Cascading dropdown AngulatJs example</legend>
    <div ng-app="mvcapp" ng-controller="IndexController">
        <div>
            Select Country :<select ng-model="country" ng-options="c.Id as c.CountryName for c in countries | orderBy:'CountryName'" ng-change="Getstate()">
                <option value="">--Select Country--</option>
            </select> {{country}}
        </div>
        <div style="margin-top: 20px;">
            Select State :<select ng-model="state" ng-options="s.Id as s.StateName for s in states" ng-change="GetCity()" style="margin-left: 20px;">
    <option value="">--Select State--</option>
</select> {{state}}
        </div> 
        <div style="margin-top: 20px;">
            Select City: <select ng-model="city" ng-options="city.Id as city.CityName for city in cities" style="margin-left: 24px;">
    <option value="">--Select City--</option>
</select> {{city}}
        </div>
    </div>
</fieldset>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>

<script>
    var angular = angular.module('mvcapp', []);
    angular.controller('IndexController', function ($scope, $http) {
        debugger
        $http({
            method: 'Get',
            url: '/Index/GetCountry'
        }).success(function (data) {
            $scope.countries = data;
        });
        $scope.Getstate = function () {
            debugger
            var CountryId_Fk = $scope.country;          
            if (CountryId_Fk) {
                $http({
                    method: 'POST',
                    url: '/Index/Getstate',
                    data: JSON.stringify({ CountryId_Fk: CountryId_Fk })
                }).success(function (data) {
                    $scope.states = data;
                })
            }          
        }
        $scope.GetCity = function () {
            debugger
            var StateId_Fk = $scope.state;
            if (StateId_Fk) {
                $http({
                    method: 'POST',
                    url: '/Index/GetCity',
                    data: JSON.stringify({ StateId_Fk: StateId_Fk })
                }).success(function (data) {
                    $scope.cities = data;
                })
            }           
        }
    });  
</script>

Save and build the project. Now run the project and test it. 


4 comments:

  1. Sir "DemoEntities1" is ADO.NET Entity model is added and DB is selected right ???
    you have not specified steps for it
    reply me if wrong
    Thanks

    ReplyDelete
  2. And please send Database structure
    because i don't understand how to declare it properly
    Thanks

    ReplyDelete
    Replies
    1. Hi Manav,
      I have uploaded the working example. Download it. It will help you.

      Delete
  3. Sir, can you please help me. i wants to select country, state and city in edit mode. all the value comes from database.

    Thanks

    ReplyDelete