In this article, I will show you how to create cascading dropdownlist in asp.net mvc using jQuery. When the user selects the first dropdown, on the dropdown change jQuery, it loads the product dropdownlist.
Create two dropdownlists category and product and create a json method Get data (GetCategories() and GetProduts()).
The GetProducts() function will return the products filtered by the categoryId selected in category dropdown by the user. The json data is bind to the product dropdownlist using jQuery for.
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 "Home" controller. Copy and paste the following code.
models db = new models();
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 2: Copy and paste the following code in the design page index.cshtml.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "/home/GetCategories",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCategory').append('<option value="' +value.CategoryID + '">' + value.CategoryName + '</option>');
});
}
});
$('#dropdownCategory').change(function () {
$('#dropdownProduct').empty();
$.ajax({
type: "POST",
url: "/home/GetProducts",
datatype: "Json",
data: { CategoryID: $('#dropdownCategory').val()},
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownProduct').append('<option value="' +value.ProductID + '">' + value.ProductName + '</option>');
});
}
});
});
});
</script>
<div style="border:1px solid #ded7d7;width:450px;height:300px">
<h2>Cascading DropDownList Sample</h2>
<br />
<div>
@Html.DropDownList("dropdownCategory", new SelectList(string.Empty, "Value", "Text"), "Please select aCategory", new { @style = "width:250px;height:30px" })
</div>
<div style="margin-top: 10px;">
@Html.DropDownList("dropdownProduct", new SelectList(string.Empty, "Value", "Text"), "Please select aProduct", new { @style = "width:250px;;height:30px" })
</div>
</div>
Ajax cascading dropdown example: