簡體   English   中英

使用Javascript / jQuery動態填充下拉列表

[英]Fill a drop down list dynamically using Javascript/jQuery

在ASP .NET MVC Razor視圖中,我有一個下拉列表,如下所示:

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

DeviceModelList只是一個SelectList。

如何根據客戶端操作(如按鈕單擊或使用Javascript / jQuery / Ajax的其他下拉選項)動態填充DeviceModelList?

您可以將此下拉列表外部化為部分:

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

對於類似的示例,您可以查看以下答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM