-->

MVC (5) Populate a dropdown based on another [dupl

2020-07-18 06:07发布

问题:

I know I can make a dropdown with a list of SelectedListItem> and @Html.DropDownList("someID") and os on..

My question is, what if you had 2 dropdowns, and the second dropdown depended on the selected item from the first dropdown?

How do you populate it? With JS? How would you go about it? Would you change the populate with another list, change the whole dropdown or maybe have a partialview for each dropdown combination, so it's a matter of replacing with the right dropdown.

回答1:

I have added NetFiddle example. Works here

I would suggest to use jquery $.getJson() to fill second dropdown without refresh to page. You can implement like following example.

//html

<select id="EventId" name="eventId">
    <option value="1">option1</option>
    <option value="2">option2</option>
    <option value="3">option3</option>
</select>

<label>Second</label>
<select id="SecondDropdown">  
</select>

// jquery

$("#EventId").on("change", function(){
    showValue($(this).val());
})

function showValue(val)
{
    console.log(val);               
    $.getJSON('@Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {                       
            $("#SecondDropdown").html(""); // makes select null before filling process
            var data = result.data;
            for (var i = 0; i < data.length; i++) {
                $("#SecondDropdown").append("<option>"+ data[i] +"</option>")
            }

    })    
}

//controller

[HttpGet]
public JsonResult GetDropdownList(int? value)
{
    List<string> yourdata = new List<string>();

    if(value == 2)
    {
        yourdata.Add("option2a");
        yourdata.Add("option2b");
        yourdata.Add("option2c");
        return Json(new { data = yourdata}, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new { data = ""}, JsonRequestBehavior.AllowGet);
    }           

}