In this article, I will show you how to create cascading dropdownlist in asp.net mvc using Angularjs. To begin install angularjs in the project by running the following command in nuget package manager console.
PM> Install-Package angularjs
Create two dropdownlists category and product and create a json method Get data (GetCategories() and GetProduts()).
Here I am using Northwind database. You can download it from following link.
Open Microsoft sql management studio and right click on the database and attach it.
Step 1: Create an ado.net entity data model using tables Categories and Products and generate entity for that.
Step 2: Right click on the "Controllers" folder and add "CascadeDll" controller. Copy and paste the following code.
public class cascadeDdlController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetCategories()
{
using (models context = new models())
{
var ret = context.Categories.Select(x => new { x.CategoryID,x.CategoryName}).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetProducts(int CategoryID)
{
using (models context = new models())
{
var ret = context.Products.Where(x => x.CategoryID ==CategoryID).Select(x => new { x.ProductID, x.ProductName }).ToList();
return Json(ret);
}
}
}
Step 3: Copy and paste the following code in the design page index.cshtml. I used cdn for angularjs.
<script type="text/javascript">
var app = angular.module('myModule', []);
app.controller('myController', function ($scope, $http) {
GetCategories();
function GetCategories() {
$http({
method: 'Get',
url: '/cascadeDdl/GetCategories'
}).success(function (data, status,headers, config) {
$scope.Categories = data;
}).error(function (data, status, headers,config) {
$scope.message = 'Unexpected Error';
});
}
$scope.GetProducts = function () {
var CategoryId = $scope.Category;
if (CategoryId) {
$http({
method: 'POST',
url: '/cascadeDdl/GetProducts',
data: JSON.stringify({CategoryID: CategoryId })
}).success(function (data, status,headers, config) {
$scope.Products = data;
}).error(function (data, status,headers, config) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states = null;
}
}
});
</script>
<div style="border:1px solid #808080;width:450px;height:300px">
<h2>dropdownlist Angularjs</h2>
<div data-ng-app="myModule">
<form name="mainForm" data-ng-submit="sendForm()" data-ng-controller="myController" novalidate>
<div class="error">{{message}}</div>
<select data-ng-model="Category" data-ng-options="c.CategoryID as c.CategoryName for c inCategories" data-ng-change="GetProducts()">
<option value="">-- Select Category --</option>
</select>
<select data-ng-model="Product" data-ng-disabled="!Products" data-ng-options="s.ProductIdas s.ProductName for s in Products">
<option value="">-- Select Product --</option>
</select>
</form>
</div>
</div>
Output: