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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7253187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:29:35  来源:igfitidea点击:

Fill a drop down list dynamically using Javascript/jQuery

javascriptjquery.netasp.net-mvcajax

提问by dnatoli

In an ASP .NET MVC Razor view, I have a dropdown list as follows:

在 ASP .NET MVC Razor 视图中,我有一个下拉列表,如下所示:

@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

DeviceModelList is just a SelectList.

DeviceModelList 只是一个 SelectList。

How can I dynamically fill the DeviceModelList depending on a client side action like a button click or another drop down selection using Javascript/jQuery/Ajax?

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

回答by Darin Dimitrov

You could externalize this dropdown into a partial:

您可以将此下拉列表具体化为部分:

@model MyViewModel
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

then in your main view include it inside some container:

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

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

then you could have a controller action which takes some parameter and based on its value it renders this partial:

那么你可以有一个控制器动作,它接受一些参数并根据它的值呈现这个部分:

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

Now the last part is to send the AJAX request to refresh the drop down list when some event occurs. For example when the value of some other ddl changes (or something else, a button click or whatever):

现在最后一部分是在发生某些事件时发送 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);
            }
        });
    });
});

Another possibility consists into using JSON. Your Foocontroller action would only return some Json object containing the new key/value collection and in the success callback of the AJAX request you would refresh the drop down list. In this case you don't need to externalize it into a separate partial. For example:

另一种可能性是使用 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
                        })
                    );
                });
            }
        });
    });
});

and finally your Foo controller action will return Json:

最后你的 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' }
    });
}

For a similar example you may take a look at the following answer.

对于类似的示例,您可以查看以下答案