使用Javascript/jQuery动态填充下拉列表

5
在一个ASP .NET MVC Razor视图中,我有一个下拉列表如下:
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

DeviceModelList只是一个选择列表。

我该如何使用Javascript/jQuery/Ajax根据客户端动作(例如按钮单击或其他下拉菜单选择)动态填充DeviceModelList?

1个回答

11
你可以将这个下拉菜单外部化为一个局部视图:
@model MyViewModel
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

然后在您的主视图中将其包含在某个容器中:

@model MyViewModel
...
<div id="ddlcontainer">
    @Html.Partial("Foo", Model)
</div>
...

那么您可以编写一个控制器操作,该操作接受某些参数,并根据其值呈现此部分视图:

public ActionResult Foo(string someValue)
{
    MyViewModel model = ... go ahead and fill your view model
    return PartialView(model);
}

现在的最后一步是,当某些事件发生时,发送AJAX请求以刷新下拉列表。例如,当其他ddl的值更改时(或其他事件,如按钮单击等):

$(function() {
    $('#SomeOtherDdlId').change(function() {
        // when the selection of some other drop down changes 
        // get the new value
        var value = $(this).val();

        // and send it as AJAX request to the newly created action
        $.ajax({
            url: '@Url.Action("foo")',
            type: 'POST',
            data: { someValue: value },
            success: function(result) {
                // when the AJAX succeeds refresh the ddl container with
                // the partial HTML returned by the Foo controller action
                $('#ddlcontainer').html(result);
            }
        });
    });
});

另一种可能性是使用JSON。您的Foo控制器操作将仅返回包含新键/值集合的某些Json对象,在AJAX请求的成功回调中,您会刷新下拉列表。在这种情况下,您不需要将其外部化为单独的部分视图。例如:

$(function() {
    $('#SomeOtherDdlId').change(function() {
        // when the selection of some other drop down changes 
        // get the new value
        var value = $(this).val();

        // and send it as AJAX request to the newly created action
        $.ajax({
            url: '@Url.Action("foo")',
            type: 'POST',
            data: { someValue: value },
            success: function(result) {
                // when the AJAX succeeds refresh the dropdown list with 
                // the JSON values returned from the controller action
                var selectedDeviceModel = $('#SelectedDeviceModel');
                selectedDeviceModel.empty();
                $.each(result, function(index, item) {
                    selectedDeviceModel.append(
                        $('<option/>', {
                            value: item.value,
                            text: item.text
                        })
                    );
                });
            }
        });
    });
});

最后,你的Foo控制器动作将会返回Json:

public ActionResult Foo(string someValue)
{
    return Json(new[] {
        new { value = '1', text = 'text 1' },
        new { value = '2', text = 'text 2' },
        new { value = '3', text = 'text 3' }
    });
}

如果您需要一个类似的示例,可以查看以下答案


使用partial是我选择的方法。谢谢! - dnatoli
@DarinDimitrov 我已经实现了你的解决方案,但是我添加了第二个ajax请求,因为根据用户下拉选择另一个ddl将填充值。我的问题是第二个ajax请求没有触发。你知道为什么吗? - codingNightmares

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接