MVC(5)根据另一个填充下拉列表 [英] MVC (5) Populate a dropdown based on another

查看:86
本文介绍了MVC(5)根据另一个填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用SelectedListItem>@Html.DropDownList("someID")以及操作系统列表进行下拉.

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

我的问题是,如果您有2个下拉菜单,而第二个下拉菜单取决于第一个下拉菜单中的所选项目,该怎么办?

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

如何填充?用JS?你会怎么做? 您是要使用另一个列表来更改填充,还是要更改整个下拉列表,或者对每个下拉列表组合都拥有部分视图,所以只需替换为正确的下拉列表即可.

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.

推荐答案

我添加了NetFiddle示例.在此处

I have added NetFiddle example. Works here

我建议使用jquery $.getJson()填充第二个下拉列表,而不刷新页面.您可以实现以下示例.

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

    })    
}

//控制器

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

}

这篇关于MVC(5)根据另一个填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆