Procedure
Open Visual Studio 2012 and select "File" -> "New" -> "Project...".
Now add a AngularJS reference. Right-click on the project in the Solution Explorer and select Manage NuGet Packages.
Now add an ADO.NET Entity Data Model.
Now add a new Controller Employee and enter the following code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using CascadingDropDownInMVC4WithAngularJS.Models;
-
- namespace CascadingDropDownInMVC4WithAngularJS.Controllers
- {
- public class EmployeeController : Controller
- {
- EmployeeManagementEntities db=new EmployeeManagementEntities();
-
- public ActionResult Index()
- {
- return View();
- }
-
- public JsonResult GetCountry()
- {
- var CountryList = db.Country.ToList();
- return this.Json(CountryList, JsonRequestBehavior.AllowGet);
- }
-
- [HttpPost]
- public JsonResult GetStates(int CountryID)
- {
- var StateList = db.State.Where(m => m.CountryID == CountryID).ToList();
-
- return this.Json(StateList);
- }
- }
- }
Now add a View on the Index Action method:
- @Scripts.Render("~/Scripts/angular.min.js")
-
- <script type="text/javascript">
- //Module
- var myApp = angular.module('myApp', []);
-
- //Controller
- myApp.controller('MainCtrl', ['$scope', '$http',
- function ($scope, $http) {
- //$http service for Getting the Country
- $http({
- method: 'GET',
- url: '/Employee/GetCountry'
- }).
- success(function (data) {
- $scope.country = data;
- });
-
- //$http service for getting States
- $scope.GetStates = function () {
- if ($scope.countr) {
- $http({
- method: 'POST',
- url: '/Employee/GetStates/',
- data: JSON.stringify({ CountryID: $scope.countr })
- }).
- success(function (data) {
- $scope.states = data;
- });
- }
- else {
- $scope.cities = null;
- }
- }
- }]);
- </script>
-
- <div data-ng-app="myApp">
- <div data-ng-controller="MainCtrl">
- <div class="editor-label">
- <label>Name</label>
- </div>
- <div class="editor-field">
- @Html.TextBox("Name")
- </div>
- <div class="editor-label">
- <label>Country</label><br />
- </div>
- <div class="editor-field">
- <select data-ng-model="countr"
- data-ng-options="c.CountryID as c.CountryName for c in country"
- data-ng-change="GetStates()">
- <option value="">--Select Country--</option>
- </select><br />
- </div>
- <div class="editor-label"><br />
- <label>State</label><br />
- </div>
- <div class="editor-field">
- <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>
-
-
- </div>
- </div>