Add 2 Class 1 for Countries and other for state.
- public class Country
- {
- public int CountryId { get; set; }
- public string CountryName { get; set; }
- }
- public class State
- {
- public int StateId { get; set; }
- public string StateName { get; set; }
- public int CountryId { get; set; }
- }
Create a ActionResult Name it as Index [Add a View].
Add the script
- <script src="~/Scripts/angular.min.js"></script>
Create a js Name it in my case its CascadingDropdown.
- var app = angular.module('myApp', []);
- app.controller('myController', function ($scope, $http) {
- getcountries();
- function getcountries() {
-
- $http({
- method: 'Get',
- url: '/Home/Countries'
-
- }).success(function (data, status, header, config) {
-
- $scope.countries = data;
- }).error(function (data, status, header, config) {
- $scope.message = "Error";
- });
- }
-
- $scope.GetStates = function ()
- {
- var countryIdselected = $scope.countrymodel;
- if (countryIdselected) {
- $http({
- method: 'Post',
- url: '/Home/States',
- data: JSON.stringify({ countryId: countryIdselected })
- }).success(function (data, status, header, config) {
- $scope.states = data;
- }).error(function (data, status, header, config) {
- $scope.message = "Error";
- })
- }
- else {
- $scope.states = null;
- }
- }
- });
-
-
-
- public ActionResult Countries()
- {
- List<Country> cobj = new List<Country>();
- cobj.Add(new Country { CountryId = 1, CountryName = "India" });
- cobj.Add(new Country { CountryId = 2, CountryName = "Srilanka" });
- cobj.Add(new Country { CountryId = 3, CountryName = "USA" });
-
- return Json(cobj, JsonRequestBehavior.AllowGet);
- }
-
-
-
- public ActionResult States(int countryId)
- {
- List<State> sobj = new List<State>();
- sobj.Add(new State { StateId = 1, StateName = "Karnataka", CountryId = 1 });
- sobj.Add(new State { StateId = 2, StateName = "Kerala", CountryId = 1 });
- sobj.Add(new State { StateId = 3, StateName = "TamilNadu", CountryId = 1 });
- sobj.Add(new State { StateId = 1, StateName = "Newyork", CountryId = 3 });
- sobj.Add(new State { StateId = 1, StateName = "Colombo", CountryId = 2 });
-
-
- var result = sobj.Where(x => x.CountryId == countryId).Select(x => new { x.StateId, x.StateName });
-
- return Json(result);
- }
-
-
-
- <div ng-app="myApp">
-
- <form name="mainForm" ng-controller="myController">
-
- <select ng-model="countrymodel" ng-options=" c.CountryId as c.CountryName for c in countries" ng-change="GetStates()">
- <option value="">-- Select Country --</option>
- </select>
- <select ng-model="statemodel" ng-options="s.StateId as s.StateName for s in states ">
- <option value="">-- Select State --</option>
- </select>
- </form>
- </div>