user5813072 user5813072 - 1 year ago 73
JSON Question

Populating dropdown menu with JSON Data in Mvc views

i am a beginner when it comes to javascript(Json). i am trying to populate a dropdown box based on the selection of another dropdown. as you can see in the image below as an example i am trying to populate the " Rule Choice " dropdown based on the "Product template" dropdown. the attempted code is also available.

Any Help would be appreciated.

thank you

function drFilter()
var productTemp = $('#ddlProdTemp :selected').val();
$.getJSON('ptdrFilter', { productTemplate: productTemp }, function (result) {
var ddl = $('#ddl2');
var length = result.length;
if (length > 0) {

.attr('value', 0)
.text("-- Please Select --")

$(result).each(function (will) {
.attr('value', result[will])

public ActionResult ptdrFilter(int id)
IUnitOfWork uow = DataAccess.GetUnitOfWork();
using (ManageProductTemplate ptLogic = new ManageProductTemplate(ref uow))
List<ProductTemplate> currentpt = ptLogic.GetBy(x => x.ProductTemplateID == id);
List<string> pt = new List<string>();
foreach (var item in currentpt)

return Json(pt);

enter image description here

Answer Source
<!DOCTYPE html>
    <meta charset="utf-8" />
    <script src=""></script>

    <select id="main">
        <option value="a">A</option>
        <option value="b">B</option>

    <select id="subselect"></select>

        var sampleData = { a: { value1: "text 1 in a", value2: "text 2 in a" }, b: { value1: "text 1 in b", value2: "text 2 in b" } };
        var dataInJSONForm = JSON.stringify(sampleData);
        var datainJSObjectForm = JSON.parse(dataInJSONForm);

        $('#main').on('change', function (e) {
            var valueChosenInMain = $(this).val();
            var options = datainJSObjectForm[valueChosenInMain];

            var $subselect = $('#subselect');
            for (var property in options) {
                $subselect.append($('<option>', { value: property, text: options[property] }));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download