Translate

Thursday, 17 December 2015

Casacading Dropdowns using Angular JS

 Cascading Dropdown using Angular JS shown below

In view


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <meta name="viewport" content="width=device-width" />
    <title>AngularJS1</title>
</head>

<div ng-app="myApp" ng-controller="MyCtrl">
    <select data-ng-model="country" data-ng-options="c.CountryId as c.CountryName for c in countries" data-ng-change="GetStates()">
        <option value="">-- Select Country --</option>
    </select>

    <select data-ng-model="state" data-ng-disabled="!states" data-ng-options="s.StateId as s.StateName for s in states">
        <option value="">-- Select State --</option>
    </select>
</div>
</html>
<script>
    var app = angular.module('myApp', []);
    app.controller('MyCtrl', function ($scope, $http) {
        $http({
            method: 'Get',
            url: '/AngularJS/GetCountries'
        }).success(function (data) {
            $scope.countries = data;
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
        });


        $scope.GetStates = function () {
          
            var countryId = $scope.country;
            alert(countryId);
            if (countryId) {
                $http({
                    method: 'POST',
                    url: '/AngularJS/GetStates/',
                    data: JSON.stringify({ countryId: countryId })
                }).success(function (data) {
                    $scope.states = data;
                }).error(function (data, status, headers, config) {
                    $scope.message = 'Unexpected Error';
                });
            }
            else {
                $scope.states = null;
            }
        }
    })
</script>



In Controller
public ActionResult AngularJS1()
        {
            return View();
        }


        public JsonResult GetCountries()
        {

                var ret = context.Countries.Select(x => new { x.CountryId, x.CountryName }).ToList();
                return Json(ret, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetStates(int countryId)
        {
                var ret = context.States.Where(x => x.CountryId == countryId).Select(x => new { x.StateId, x.StateName }).ToList();
                return Json(ret);
        }


No comments:

Post a Comment