Cascading Country, State and City DropDownLists using AngularJS in ASP.Net MVC
Introduction:
Today in this article, I will explain How to implement Cascading Country, State and City DropDownLists using AngularJS in ASP.Net MVC.
Earlier I posted about Country State and City dropdownlist using Jquery Ajax in Asp.net MVC. In this article, I used Ado.net as database operation and Razor view engine for the user interface. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change of state dropdown.
Follow these steps in order to implement “Country, State and City dropdownlist using AngularJS in Asp.net MVC”
Step1: Create New Project.
Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty template > then click to ok
Step2: Create a table and Stored procedure in the database.
In this example, I have created following tables and stored procedures for binding Country, State, and City dropdownlists.
Create ‘tbl_Country’ table for getting the record of Country table.
CREATE TABLE [dbo].[tbl_Country] (
[Country_id] INT IDENTITY (1, 1) NOT NULL,
[Country_Name] NVARCHAR (50) NULL,
CONSTRAINT [PK_tbl_Country] PRIMARY KEY CLUSTERED ([Country_id] ASC)
);
The design of the table look like this as follows:
Now create 'tbl_state' table for the State record.
CREATE TABLE [dbo].[tbl_state] (
[State_id] INT NOT NULL,
[Country_id] INT NULL,
[State] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_tbl_state] PRIMARY KEY CLUSTERED ([State_id] ASC)
);
The design of the table look like this as follows:
In last we create tbl_city for City Record
CREATE TABLE [dbo].[tbl_city] (
[City_id] INT NOT NULL,
[State_id] INT NULL,
[City] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_tbl_city] PRIMARY KEY CLUSTERED ([City_id] ASC)
);
The design of the table look like this as follows:
Now I have created stored procedures for fetching the record on the behalf of their values
Country Record:
Create proc Sp_Country_get
as
begin
Select * from tbl_Country
End
State Record:
Create proc Sp_state_get
@country_id int
as
begin
Select * from tbl_state where Country_id=@country_id
end
City Record:
Create proc Sp_city_get
@city_id int
as
begin
Select * from tbl_city where State_id=@city_id
end
Step3: Add Connection string in web.config file
Here I have to add connection string in ‘web.config’ file under Configuration section as follows
<connectionStrings>
<add name="con" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step4: Create a controller.
Go to Solutions Explorer > right click on controller folder > Add Controller > Enter Controller name > Select template “empty MVC Controller ” > Add.
Here I have created a controller “HomeController”
Step5: Create a class for Database operation.
Here in this example, I have used Ado.net as database operation so we need to create a class for all database operations. Here I have created ‘db.cs’ class.
Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘Database_Access_Layer’) > right click on folder > Add new class.
Now write the following code snippet given below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace CountryStatecityAngular.Database_Access_Layer
{
public class db
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
// Get country record
public DataSet getCountry()
{
SqlCommand com = new SqlCommand("Sp_Country_get", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
//Get State record
public DataSet getstate(string countryid)
{
SqlCommand com = new SqlCommand("Sp_state_get", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@country_id", countryid);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
// Get city record
public DataSet getCity(string stateid)
{
SqlCommand com = new SqlCommand("Sp_city_get", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@city_id", stateid);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
In the above I have created three functions, first one is ‘getCountry’, It is used to find all country name form database and second function ‘getstate’ for fetching the record on the basis of CountryID and third function ‘getCity’ for fetching the record on the basis of StateID.
Step6: Add model class for dropdown records.
Go to Solutions Explorer > right click on Model > Add new class (Here I have to add dropdown.cs).
Now write the following code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CountryStatecityAngular.Models
{
public class Countrylist
{
public int Country_id { get; set; }
public string Country { get; set; }
}
public class Statelist
{
public int State_id { get; set; }
public int Country_id { get; set; }
public string State { get; set; }
}
public class Citylist
{
public int City_id { get; set; }
public int State_id { get; set; }
public string City { get; set; }
}
}
Step7: Add methods in the controller.
Here I have created following methods in HomeController that has following code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CountryStatecityAngular.Models;
using System.Data;
namespace CountryStatecityAngular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
Database_Access_Layer.db dblayer = new Database_Access_Layer.db();
public ActionResult Index()
{
return View();
}
// Get Country record
public JsonResult Get_Country()
{
DataSet ds = dblayer.getCountry();
List<Countrylist> listcountry = new List<Countrylist>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
listcountry.Add(new Countrylist
{
Country_id = Convert.ToInt32(dr["Country_id"]),
Country = dr["Country"].ToString()
});
}
return Json(listcountry, JsonRequestBehavior.AllowGet);
}
// Get State record
public JsonResult Get_state(string countryid)
{
DataSet ds = dblayer.getstate(countryid);
List<Statelist> liststate = new List<Statelist>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
liststate.Add(new Statelist
{
State_id = Convert.ToInt32(dr["State_id"]),
State = dr["State"].ToString()
});
}
return Json(liststate, JsonRequestBehavior.AllowGet);
}
// Get City Record
public JsonResult Get_City(string stateid)
{
DataSet ds = dblayer.getCity(stateid);
List<Citylist> listcity = new List<Citylist>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
listcity.Add(new Citylist
{
City_id = Convert.ToInt32(dr["City_id"]),
City = dr["City"].ToString()
});
}
return Json(listcity, JsonRequestBehavior.AllowGet);
}
}
}
In above code, I have created three JSON return types methods that get the record on the behalf of respected keys.
Step8: Add New JS file for AngularJS Controller and AngullarJS library file
Go to Solution Explorer > Right Click on the folder (where you want to save your AngularJS controller JS file, here I have created a folder named "AngularController" under scripts Folder) > Add > Select Javascript file > Enter name > Add.
Now write the following code snippet
var app = angular.module('Homeapp', []);
app.controller('HomeController', function ($http, $scope) {
//Get Country record
$http.get('/Home/Get_Country').then(function (d) {
$scope.countrylist = d.data;
}, function () {
alert('failed');
});
// Get State record
$scope.state = function () {
$http.get('/Home/Get_state?countryid=' + $scope.CountryId).then(function (d) {
$scope.statelist = d.data;
});
};
// Get City record
$scope.city = function () {
$http.get('/Home/Get_City?stateid=' + $scope.StateID).then(function (d) {
$scope.citylist = d.data;
});
};
});
Here I have created an angular controller named as ‘HomeController’ with parameter $http and $scope
$http: $http is an AngularJS service for reading data from remote servers. It makes a request to the server and returns a response.
$Scope: $Scope is the binding part between the HTML (view) and the JavaScript (controller). It is an object with the available properties and methods. $Scope is available for both the view and the controller.
Step9: Add view for action in the controller.
Right Click on Action Method > Add View > Enter View Name (Here I add Index) > Select View Engine (Razor) > Add.
It has following code and design.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div ng-app="Homeapp" ng-controller="HomeController">
<br />
<select ng-model="CountryId" ng-change="state()">
<option value="">Select Country</option>
<option data-ng-repeat="t in countrylist" value="{{t.Country_id}}">{{t.Country}}</option>
</select><br /><br />
<select ng-model="StateID" ng-change="city()">
<option value="">Select State</option>
<option data-ng-repeat="t in statelist" value="{{t.State_id}}">{{t.State}}</option>
</select><br /><br />
<select ng-model="Cityid">
<option value="">Select City</option>
<option data-ng-repeat="t in citylist" value="{{t.City_id}}">{{t.City}}</option>
</select>
</div>
<script src="~/scripts/angular.min.js"></script>
<script src="~/scripts/AngularController/HomeController.js"></script>
</body>
</html>
- ng-model: which will bind the model country, state properties
- data-ng-repeat: Repeat the options on the behalf of the number of records fetched.
- ng-change: is the event to fill the state and city list for the selected country
Step 10: Run Application.
We have done all steps, now it’s time to run the application
If you have any problem and face any difficulty then Share your experiences with us in the comments below!
Like this post? Don’t forget to share it!