dna*_*oli 5 .net javascript ajax asp.net-mvc jquery
在ASP .NET MVC Razor视图中,我有一个下拉列表,如下所示:
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)
Run Code Online (Sandbox Code Playgroud)
DeviceModelList只是一个SelectList.
如何根据客户端操作(如按钮单击或使用Javascript/jQuery/Ajax的其他下拉选项)动态填充DeviceModelList?
Dar*_*rov 11
您可以将此下拉列表外部化为部分:
@model MyViewModel
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)
Run Code Online (Sandbox Code Playgroud)
然后在你的主视图中将它包含在一些容器中:
@model MyViewModel
...
<div id="ddlcontainer">
@Html.Partial("Foo", Model)
</div>
...
Run Code Online (Sandbox Code Playgroud)
然后你可以有一个控制器动作,它采取一些参数,并根据它的值,它呈现这个部分:
public ActionResult Foo(string someValue)
{
MyViewModel model = ... go ahead and fill your view model
return PartialView(model);
}
Run Code Online (Sandbox Code Playgroud)
现在最后一部分是发送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);
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用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
})
);
});
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
最后你的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' }
});
}
Run Code Online (Sandbox Code Playgroud)
对于类似的示例,您可以查看以下答案.