Cascading Dropdown Lists with JSON Result
To do a Cascading or dependent dropdownlist we start with a bound dropdownlist - could look something like this:
The objective is to create or bind another dropdown after the selection of the networkId
<select id="programId" name="programId" class="form-control"></select>
Begin by adding the following function to your page - this clears any existing results, pulls in new results and populates our 2nd dropdownlist (programid)
$(function () {
The last thing we need is to look at our JsonResult query
@Html.DropDownList("networkId", null, "Select a Network", htmlAttributes: new { @class = "form-control" })
So first we need to add a placeholder:
There are several ways to do this but we are going to do it with Jquery and a JsonResult in our controller.
$('#networkId').change(function () {
$('#programid').html("");
$.getJSON('/Requests/ProgramList/' + $('#networkId').val(), function (data) {
var items = '<option>Select a Program</option>';
$.each(data, function (i, programs) {
items += "<option value='" + programs.Value + "'>" + programs.Text + "</option>";
});
$('#programId').html(items);
});
});
});
public JsonResult Products(int Id)
{
var products = (from s in db.Products
where s.programId == Id
select s);
return Json(new SelectList(products.ToArray(), "productId", "description"),
JsonRequestBehavior.AllowGet);
}
The objective is to create or bind another dropdown after the selection of the networkId
<select id="programId" name="programId" class="form-control"></select>
Begin by adding the following function to your page - this clears any existing results, pulls in new results and populates our 2nd dropdownlist (programid)
$(function () {
The last thing we need is to look at our JsonResult query
@Html.DropDownList("networkId", null, "Select a Network", htmlAttributes: new { @class = "form-control" })
So first we need to add a placeholder:
There are several ways to do this but we are going to do it with Jquery and a JsonResult in our controller.
$('#networkId').change(function () {
$('#programid').html("");
$.getJSON('/Requests/ProgramList/' + $('#networkId').val(), function (data) {
var items = '<option>Select a Program</option>';
$.each(data, function (i, programs) {
items += "<option value='" + programs.Value + "'>" + programs.Text + "</option>";
});
$('#programId').html(items);
});
});
});
public JsonResult Products(int Id)
{
var products = (from s in db.Products
where s.programId == Id
select s);
return Json(new SelectList(products.ToArray(), "productId", "description"),
JsonRequestBehavior.AllowGet);
}
Comments