几周前我陷入了同样的困境:-
让您的 MVC 调用如下:-
private void LoadDropdown1()
{
var _data;//Your logic to get the data
ViewData["Dropdown1"] = new SelectList(_data, "Dropdown1Id", "Name");
}
private void LoadDropdown2(int dropdownParameterId)
{
var _data = "";//Use your ID to get the data
ViewData["Dropdown2"] = new SelectList(_data, "Dropdown2Id", "Name");
}
你的 .cshtml 是:-
@using (Html.BeginForm())
{
<div>
<table>
<tr>
<td><b>Select a District:</b></td>
<td>@Html.DropDownListFor(m => m.Dropdown1Id, ViewData["Dropdown1"] as IEnumerable<SelectListItem>, "Select One", new {@id="Dropdown1Id"})</td>
</tr>
<tr>
<td><b>Select:</b></td>
<td>@Html.DropDownListFor(m => m.Dropdown2Id, ViewData["Dropdown2"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
现在 AJAX 调用最好将数据加载到您的下拉列表中:-
$(function () {
$('select#Dropdown1').change(function () {
var id = $(this).val();
$.ajax({
url: 'Bla Bla',
type: 'POST',
data: JSON.stringify({ id: id }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, data) {
$('select#Dropdown1').append('<option value="0">Select One</option>');
// loop through the LoadDropdown1 and fill the dropdown
$.each(data, function (index, item) {
$('select#Dropdown1').append(
'<option value="' + item.Id + '">'
+ item.Name +
'</option>');
});
});
}
});
});
});
我想说的是.. 以您喜欢的方式加载您的第一个下拉列表。然后在第一个下拉列表的更改事件中,您可以触发一个 ajax 调用来获取第二个下拉列表的数据......同样......
参考: -在选择更改事件 - Html.DropDownListFor