MVC (5) Populate a dropdown based on another [duplicate]

两盒软妹~` 提交于 2020-01-01 15:55:55

问题


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);
    }           

}


来源:https://stackoverflow.com/questions/44847579/mvc-5-populate-a-dropdown-based-on-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!