Angularjs Cascading Dropdown with Asp.Net MVC
Cascading dropdown with angularjs is easier than MVC and ASP.Net. 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. We will fetch only those records from database which match the criteria rather than filtering in controller. I already create example here.
Step 1 : First Create database query to select country , state and city like below.
ALTER PROCEDURE [dbo].[getCountry]
AS
BEGIN
select * from tbCountry
END
ALTER PROCEDURE [dbo].[getState]
@CountryId int
AS
BEGIN
select * from tbState where CountryId=@CountryId
END
ALTER PROCEDURE [dbo].[getCity]
@StateId int
AS
BEGIN
select * from tbCity where StateId=@StateId
END
AS
BEGIN
select * from tbCountry
END
ALTER PROCEDURE [dbo].[getState]
@CountryId int
AS
BEGIN
select * from tbState where CountryId=@CountryId
END
ALTER PROCEDURE [dbo].[getCity]
@StateId int
AS
BEGIN
select * from tbCity where StateId=@StateId
END
Step 2 : Create Module.js file and codelike below
var myapp;
(function () {
myapp = angular.module('MyApps', []);
})();
(function () {
myapp = angular.module('MyApps', []);
})();
Step 3 : Create Service.js File and add code like below
myapp.service('myService', function ($http) {
this.getCountryData = function () {
debugger;
return $http.get('/Registration/GetCountry');
}
// get states
this.getStateData = function (CountryId) {
debugger;
var Resp = $http({
method: "post",
url: "/Registration/GetState",
params: {
CountryId: CountryId
},
dataType: "json"
});
return Resp;
}
// get city
this.getCityData = function (StateId) {
debugger;
var Resp = $http({
method: "post",
url: "/Registration/GetCity",
params: {
id: StateId
},
dataType: "json"
});
return Resp;
}
this.getCountryData = function () {
debugger;
return $http.get('/Registration/GetCountry');
}
// get states
this.getStateData = function (CountryId) {
debugger;
var Resp = $http({
method: "post",
url: "/Registration/GetState",
params: {
CountryId: CountryId
},
dataType: "json"
});
return Resp;
}
// get city
this.getCityData = function (StateId) {
debugger;
var Resp = $http({
method: "post",
url: "/Registration/GetCity",
params: {
id: StateId
},
dataType: "json"
});
return Resp;
}
Step 4 : Create Controller.js file and code below.
myapp.controller('RegistrationController', function ($scope, myService) {
GetCountry();
//To Get All Records
function GetCountry() {
var getData = myService.getCountryData();
getData.then(function (emp) {
$scope.Countries = emp.data;
}, function () {
alert('Error while getting records');
});
}
// get state
$scope.GetStates = function () {
$scope.State = "";
var CountryId = $scope.Country;
var getData = myService.getStateData(CountryId);
getData.then(function (emp) {
$scope.States = emp.data;
}, function () {
alert('Error while getting records');
});
}
// get city
$scope.GetCity=function() {
var StateId = $scope.State;
debugger;
var getData = myService.getCityData(StateId);
debugger;
getData.then(function (emp) {
$scope.Cities = emp.data;
}, function () {
alert('Error while getting records');
});
}
});
GetCountry();
//To Get All Records
function GetCountry() {
var getData = myService.getCountryData();
getData.then(function (emp) {
$scope.Countries = emp.data;
}, function () {
alert('Error while getting records');
});
}
// get state
$scope.GetStates = function () {
$scope.State = "";
var CountryId = $scope.Country;
var getData = myService.getStateData(CountryId);
getData.then(function (emp) {
$scope.States = emp.data;
}, function () {
alert('Error while getting records');
});
}
// get city
$scope.GetCity=function() {
var StateId = $scope.State;
debugger;
var getData = myService.getCityData(StateId);
debugger;
getData.then(function (emp) {
$scope.Cities = emp.data;
}, function () {
alert('Error while getting records');
});
}
});
Step 5 : Now Create controller with RegistrationController and add code to controller action method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace AngularJs_Practicle.Controllers
{
public class RegistrationController : Controller
{
//
// GET: /Registration/
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
public ActionResult Register()
{
return View();
}
public JsonResult GetCountry()
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getCountry", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["CountryName"].ToString(), Value = @dr["CountryId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
public JsonResult GetState(string CountryId)
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getState", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CountryId", SqlDbType.Int);
cmd.Parameters["@CountryId"].Value = Convert.ToInt16(CountryId);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["StateName"].ToString(), Value = @dr["StateId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCity(string id)
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getCity", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StateId", SqlDbType.Int);
cmd.Parameters["@StateId"].Value = Convert.ToInt16(id);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["CityName"].ToString(), Value = @dr["CityId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace AngularJs_Practicle.Controllers
{
public class RegistrationController : Controller
{
//
// GET: /Registration/
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
public ActionResult Register()
{
return View();
}
public JsonResult GetCountry()
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getCountry", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["CountryName"].ToString(), Value = @dr["CountryId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
public JsonResult GetState(string CountryId)
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getState", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CountryId", SqlDbType.Int);
cmd.Parameters["@CountryId"].Value = Convert.ToInt16(CountryId);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["StateName"].ToString(), Value = @dr["StateId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCity(string id)
{
List<SelectListItem> lst = new List<SelectListItem>();
con.Open();
SqlCommand cmd = new SqlCommand("getCity", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StateId", SqlDbType.Int);
cmd.Parameters["@StateId"].Value = Convert.ToInt16(id);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new SelectListItem { Text = @dr["CityName"].ToString(), Value = @dr["CityId"].ToString() });
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
}
}
Step 6 : Now create View register,cshtml
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="~/Angularjs/Module.js"></script>
<script src="~/Angularjs/Service.js"></script>
<script src="~/Angularjs/Controller.js"></script>
<div >
<div ng-app="MyApps" ng-controller="RegistrationController">
<table>
<tr>
<td ><b>Country</b></td>
<td>
<select name="Country" ng-model="Country" ng-change="GetStates()">
<option value="">-- Select Country--</option>
<option ng-repeat="item in Countries" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td ><b>State</b><State/td>
<td>
<select ng-model="State" ng-change="GetCity()">
<option value="">-- Select State --</option>
<option ng-repeat="item in States" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td ><b>City</b></td>
<td>
<select name="City" ng-model="City" >
<option value="">-- Select City --</option>
<option ng-repeat="item in Cities" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
</table>
</div>
</div>
<script src="~/Angularjs/Module.js"></script>
<script src="~/Angularjs/Service.js"></script>
<script src="~/Angularjs/Controller.js"></script>
<div >
<div ng-app="MyApps" ng-controller="RegistrationController">
<table>
<tr>
<td ><b>Country</b></td>
<td>
<select name="Country" ng-model="Country" ng-change="GetStates()">
<option value="">-- Select Country--</option>
<option ng-repeat="item in Countries" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td ><b>State</b><State/td>
<td>
<select ng-model="State" ng-change="GetCity()">
<option value="">-- Select State --</option>
<option ng-repeat="item in States" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
<tr>
<td ><b>City</b></td>
<td>
<select name="City" ng-model="City" >
<option value="">-- Select City --</option>
<option ng-repeat="item in Cities" value="{{item.Value}}">
{{item.Text}}
</option>
</select>
</td>
</tr>
</table>
</div>
</div>
Hi, friend if you need to code or need help re-guarding this Angularjs article than feel free to contact or attached your email in comment section.
See Other Tutorial :
* AngularJS CRUD Operation : Select Insert Edit Update and Delete using AngularJS in ASP.Net MVC
* AngularJS With ASP.NET MVC
* Convert Rows to columns using 'Pivot' in SQL Server
* Mvc Registration page With user exist using Ajax method
* MVC 4 How to Perform Insert Update Delete Edit Select Operation
* MVC4 Edit,update,Delete,cancel inside gridview using sql database
* MVC 4 Gridview To Display Data Using SQL Server Database With Simple code
* Login page in asp.net Mvc4 Web application
* Mvc4 How to bind Dropdown List using Sql Database
* Gridview find control in asp.net
Sign up here with your email
ConversionConversion EmoticonEmoticon