4

我有一个包含两个@Html.DropDownListFor助手的视图:

 <div class="editor-field">
        @Html.DropDownListFor(model => model.Employee, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl1"})
        @Html.ValidationMessageFor(model => model.Employee)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.Employee2, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl2"})
        @Html.ValidationMessageFor(model => model.Employee2)
    </div>

它们的填充方式如下:

public ActionResult Create()
    {
        List<Employees> emps = new List<Employees>();
        emps.Add(new Employees { Id = 0, Name = "Michael Jordan" });
        emps.Add(new Employees { Id = 1, Name = "Magic Johnson" });
        emps.Add(new Employees { Id = 2, Name = "Larry Bird" });

        var items = emps.Select(i => new SelectListItem
        {
            Value= i.Id.ToString(),
            Text =i.Name
        });
        ViewBag.emps = items;
        return View();
    }

如何从第二个 DDL 中删除第一个 DDL 的选定项?我设法使用这样的jQuery获取选定的项目:

<script type="text/javascript">
$(function () {
    $("#ddl1").change(function () {
        alert($("#ddl1").val());
    });
});
</script>

但是,我找不到将它用于我的目的的方法。

4

2 回答 2

3

像这样的东西必须为你工作:

$(function(){
    var lists = $('#ddl1, #ddl2');
    lists.change(function(){
        var elm = $(this);
        lists.find('option').show();
        var option = lists.not('#' + this.id)
            .find('option[value="' + elm.val() +'"]').hide();

        if(option.is(':selected'))
        {
            var select = option.closest('select');
            select.val(select.find('option:visible:first').val());
        }
    });
});

Link for demo: jsfiddle.net

Added: Posted solution have problems with IE, alternative way is use disabled attribute: jsfiddle.net/cxZ2H/1/

于 2012-09-17T19:14:08.213 回答
2

这绝对是一个客户端脚本问题,而不是服务器端 ASP.NET MVC 问题。

这是我的建议:

  1. 在服务器端创建您的项目列表。
  2. 但是当你把它带给客户时,保留一个不可变的主副本。使用它来填充您的第一个select.
  3. 当用户从第一个列表中选择一个项目时,对第一个列表进行克隆,减去所选项目。

这是一个 JSFiddle:http: //jsfiddle.net/Fsf7g/1/

于 2012-09-17T18:53:31.943 回答