gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:53:14 25 4
gpt4 key购买 nike

在 ASP .NET MVC Razor View 中,我有一个下拉列表如下:

@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>
...

然后你可以有一个 Controller Action ,它接受一些参数并根据它的值呈现这个部分:

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 Controller 操作只会返回一些包含新键/值集合的 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 Controller 操作将返回 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' }
});
}

对于类似的示例,您可以查看 following answer .

关于javascript - 使用 Javascript/jQuery 动态填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7253187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com