Friday, 15 January 2016

Cascading Dropdown list Using Angularjs in MVC4

Cascading Dropdown list Using Angularjs in MVC4. In this post, I would like to explain How to implement Cascading DropDownList wi... thumbnail 1 summary

Cascading Dropdown list Using Angularjs in MVC4.

In this post, I would like to explain How to implement Cascading DropDownList with AngularJS and ASP.NET MVC.

we need to display DropDownLists in our web page such that values in one DropDownList are dependent on the value selected in another DropDownList.

step-1 :- 
Create Database into two table country and state

open database > Right click on table > add new table > add column name > save > enter table name > ok

here, i have used two table (country and state) like below..




step-2:-

Create Entity data model
Here i have explained about how to create entity data model.  click here

step-3:-

Add new controller into controller folder

Right click on controller folder > add > click on controller > now Enter name of controller > select Empty mvc controller > Add

follow below image...




Step-4:-

Now add new action into controller for fatch data from database
Here i have added two action "GetCountry" and "GetStateByCountryID" please write this following code.....
using CascadingDropDownUsingAngularJs.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CascadingDropDownUsingAngularJs.Controllers
{
 public class CascadingDropdownController : Controller
 {
     DataBaseEntities db = new DataBaseEntities();
     public ActionResult Index()
     {
       return View();
     }
     public JsonResult GetCountry()
     {
        List<Country> _GetCountry = new List<Country>();
        try
        {
           _GetCountry = db.Countries.Where(x => x.CountryId != null).ToList();
            return new JsonResult { Data = _GetCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
      public JsonResult GetStateByCountryID(int p_CountryId)
      {
        try
        {
           List<State> _GetState = db.States.Where(x => x.CountryId == p_CountryId).ToList();
           return new JsonResult { Data = _GetState, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        catch (Exception ex)
        {
           throw ex;
        }
     }
   }
}

step-5:-
Install angularjs package. here i have explained about install angularjs package

You can download AngularJS library files form click here.

Otherwise you can add project solution on visual studio following below step......

Go to solution explore> right click on project solution > click on manage nuget package > search text online "angularjs" > click to install



step-6:-
add a new three javascript file(module.js, controller.js and factory.js) on "AngulrJs" folder under Script folder

Go to solution explorer > Right click on "Angularjs" folder under Script folder > add > select javascript file > enter name of the file > Add

Now, lets move on write the following code for particluar file....

Module.Js :- 
var ModuleApp = angular.module('myapp',[]);

Controller.Js :-

ModuleApp.controller('DropDownController', ['$scope', 'Dropdownfactory', function ($scope, Dropdownfactory) {

//get list of country
var response = Dropdownfactory.GetCountry();
response.success(function (successdata) {
$scope.Country = successdata;
})

//get list of state by countryId
$scope.GetState = function (CountryID) {
var response = Dropdownfactory.GetState(CountryID);
response.success(function (successdata) {
$scope.States = successdata;
})
}

}]);

Factory.Js :-
ModuleApp.factory('Dropdownfactory', function ($http) {

  return {
       GetCountry: function () {
       return $http({
       url: "/CascadingDropdown/GetCountry",
       method: "GET",
     });
   },
     GetState: function (countruId) {
     return $http({
     url: "/CascadingDropdown/GetStateByCountryID",
     method: "POST",
     data: { p_CountryId: countruId }
     });
   }
 }
});

Step-7:-


Add a view for "Index" Action method
Right click on Index action method > Add view > Enter view name > Add


Write following code...

@{
 ViewBag.Title = "Index";
}
<body ng-app="myapp">
  <div ng-controller="DropDownController">
  <h2>Cascading DropdownList using angularjs with asp.net mvc</h2>

   Country :
    <select ng-model="CountryID" ng-options="country.CountryId as country.CountryName for country in Country" ng-change="GetState(CountryID)">
    <option value="">Select Country</option>
    </select>

    State:
    <select ng-model="StateID" ng-options="State.StateId as State.StateName for State in States">
    <option value="">Select Country</option>
 </select>
 </div>
</body>
@section scripts{
      <script src="~/Scripts/angular.min.js"></script>
      <script src="~/Scripts/AngularJs/Module.js"></script>
      <script src="~/Scripts/AngularJs/Controller.js"></script>
      <script src="~/Scripts/AngularJs/factory.js"></script>
}

ng-change="GetState(CountryID)":-



to call GetStates method on selection change of Country dropdown.
Now run this application...

Thnx for watching.....please share with your friends...
any query write comment below...

3 comments

  1. I was searching for having this same functionality with AngularJS 2 but didn't find anything. Then I come across this article. Thought of sharing with you and your reader as it will be useful for others.

    http://www.talkingdotnet.com/cascading-dropdown-select-list-using-angular-js-2/

    ReplyDelete
  2. Its not working... it is not showing me country names in dropdown..

    ReplyDelete