'Creating dropdowns according to the database

There are different properties for 3 (x,y,z) properties in my database. I created a dropdown and according to the selection I will make in the dropdown, I want to bring the properties belonging to this property in the database with another dropdown.

(For example I have x, y,z properties. X has ( a,b) , y has (c,d) , z has ( e,f) properties. When I choose the x property in dropdown I want to see a and b properties in the next dropdown. If I choose y property, c and d properties will show up in the next dropdown.)

Beginning of My Code

<form id="CareModal">
    @Html.HiddenFor(model => model.PersonID)
   
    @Html.Hidden("DoesAddictionExist", false)

    @Html.DropDownList("AddictionStatusID", (IEnumerable<SelectListItem>)ViewBag.AddictionStatus, null, new { @class = "form-control", @onchange = "AddictionChanged(this.value)" })

</form>

Someone said I should use Ajax but I don't know how.



Solution 1:[1]

Wherever you want the second dropdown to be put:

<select class="form-control" data-val="true" id="AN ID" name="A NAME (NOT NEEDED)"></select>

In your AddictionChanged method, make an ajax call to the controller.

Something like:

        var json = '{dropdownId: ' + //Value passed into function  + '}';

        $.ajax({
        url: '@Url.Action("// Method", "// Controller")',
        type:'POST',
        data: json,
        success: function(result){
            // Do whatever
                        //Create a markup for a select
            var markup = "<option Value='0'>Select option</option>";

            //Populate the markup
            for (var i = 0; i < result.length; i++) {
                markup += "<option Value=" + result[i].Value + ">" + result[i].Text + "</option>";
            }

            //Populate dropdown with value
            $("#//DROPDOWNLIST ID").html(markup).show();
        }
    });

So this calls the controller (that has the parameter dropdownId), passes it an id (whatever you are passing to this function). You, in your controller, would call a service/ db (Not sure how you project is structured) and return a list to this ajax/js function. The code inside the success creates the markup and inserts it inside a dropdown.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JamesS