在MVC中创建了两个下拉列表。当用户在第一个下拉列表中选择某些内容时,我想重新填充第二个下拉列表。
在页面加载时,我正在填充第二个下拉列表,如下所示:
// Finds selected value
var selectedItem = departureRouteSelectList.First().Value.Substring(2, 2);
// Create new selectList for returnRoute
var returnRouteSelectList = Model.RoutesListConversely
.Where(x => x.Value.StartsWith(selectedItem))
.Select(x => new SelectListItem() { Text = x.Text, Value = x.Value });
第一行找到我在Model.RoutesListConversely
上用来比较的最后两个字母。第二行根据它使用两个字母找到的内容创建列表returnRouteSelectList
。
可以使用JavaScript中的onChange()
方法完成吗?因此,当您选择某些内容时,此方法会运行并重新填充第二个下拉列表吗?
代码:
<p>
@Html.Label("Departure route:")
@Html.DropDownListFor(m => m.Departureroute, departureRouteSelectList,
new { @class = "dropdownlist", @id = "departureroute" })
</p>
<p>
@Html.Label("Return route:")
@Html.DropDownListFor(m => m.Returnroute, returnRouteSelectList,
new { @class = "dropdownlist", @id = "returnroute" })
</p>
更新
尝试使用此代码解决此问题..但问题是它不附加数据,但清除功能正在运行。
// Getting value from departure dropdown
$("#departureroute").change(function () {
}).change(populateList);
function populateList() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
// Gets the value from the departure route
var selectedId = $("#departureroute").selectedItem.value;
var returnlist = $("#returnroute");
$("#departureroute").each()
{
if (word == selectedId.substring(2)) {
returnlist.append("#departureroute")
}
}
}
答案 0 :(得分:1)
我设法使用jquery each()函数解决我的问题并追加。
以下代码可以解决问题:
// On change departure route dropdown list
$("#departureroute").change(function () {
}).change(populateReturnlist);
function populateReturnlist() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
var returnlist = $("#returnroute");
$("#departureroute option").each(function () {
// Gets the value from the departure route
var selectedId = this.value.substring(0, 2);
// Checks so the right routes gets added to list
if (selectedId === word) {
returnlist.append("<option>" + this.text + "</option>")
}
});
};