user5813072 user5813072 - 2 months ago 7
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;
ddl.empty();
if (length > 0) {

$(document.createElement('option'))
.attr('value', 0)
.text("-- Please Select --")
.appendTo(ddl);
}

$(result).each(function (will) {
//
$(document.createElement('option'))
.attr('value', result[will])
.text(result[will])
.appendTo(ddl);
});
});
}


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)
{
pt.Add(item.DistributionRule.Name);

}
return Json(pt);
}
}


enter image description here

Answer
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.1.0.slim.min.js"></script>
</head>
<body>

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

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

    <script>
        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');
            $subselect.children().detach();
            for (var property in options) {
                $subselect.append($('<option>', { value: property, text: options[property] }));
            }   
        });
    </script>
</body>
</html>