使用Javascript/jQuery动态填充下拉列表
Fill a drop down list dynamically using Javascript/jQuery
在asp.net MVC Razor视图中,我有如下的下拉列表:
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)
DeviceModelList只是一个SelectList。
我如何动态地填写DeviceModelList取决于客户端操作,如一个按钮点击或另一个下拉选择使用Javascript/jQuery/Ajax?
你可以将这个下拉列表外部化到局部:
@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' }
});
}
一个类似的例子,你可以看看下面的答案
相关文章:
- 无法使用国家/地区选择中的状态动态填充下拉列表
- 通过使用AngularJs进行分组来填充下拉列表
- 如何填充下拉列表,从javascript中的另一个下拉列表中排除任何一个选项
- 使用 MySQL 条目填充下拉列表
- 如何使用其他下拉列表中未选择的选项填充下拉列表
- 使用jquery动态填充下拉列表
- 在AngularJS中动态填充下拉列表
- 使用数据库返回的数据动态填充下拉列表
- 设置 AJAX 调用和填充下拉列表
- 使用 ajax 和 JSP Servlet 根据选择的上一个下拉列表填充下拉列表
- 在 JavaScript 中使用 MySQL 数据库中的数据填充下拉列表
- 如何在 jQuery 中用 JSON 数据填充下拉列表作为 ajax 响应
- 使用 ajax 用 SQL 填充下拉列表
- 如何使用 JavaScript 中的值填充下拉列表
- 如何在信息窗口中填充下拉列表(谷歌地图API v3)
- 从 Javascript 和 Java 返回的数组中填充下拉列表
- 使用 AJAX 和 ORACLE 以及不使用 php 填充下拉列表(选择 )
- 单击第一项时重新填充下拉列表
- 尝试使用 jquery 和 ajax 填充下拉列表
- 如何使用 javascript 清空下拉列表后重新填充下拉列表