[英]How to filter One select based on Another select drop down jquery MVC?
我有兩個選擇通過 ViewData 填充視圖,
在看來,
@{
IEnumerable<Region> region = ViewData["regions"] as IEnumerable<Region>;
IEnumerable<City> city = ViewData["cities"] as IEnumerable<City>;
}
<tfoot>
<tr>
<td><input type="text" id="txtTribeName" /></td>
<td>
<select id="ddlregion" name="RegionId">
<option value="0">Select Region</option>
@foreach (Region re in region)
{
<option value="@re.RegionID">@re.RegionName</option>
}
</select>
</td>
<td>
<select id="ddlcity" name="CityId">
<option value="0">Select City</option>
@foreach (City re in city)
{
<option value="@re.CityID">@re.CityName</option>
}
</select>
</td>
@*<td>@Html.dropDropDownListFor(ViewData["regions"] as IEnumerable<SelectListItem>)</td>*@
<td><input type="button" id="btnAdd" value="Add" /></td>
</tr>
</tfoot>
我的腳本就像,
$("body").on("change", "#ddlregion", function () {
});
在使用IEnumerable<City> city
腳本中,我可以根據地區對其進行排序嗎
希望給點建議。
編輯:
我的控制器從 Ef 傳遞區域和城市,例如,
TribeEntities Db = new TribeEntities();
ViewData["regions"] = Db.Regions;
ViewData["cities"] = Db.Cities;
在您的城市下拉菜單中,我們需要添加一個數據屬性。 我使用了data-region
。 將此用作您的城市下拉菜單;
<select id="ddlcity" name="CityId">
<option value="0">Select City</option>
@foreach (City re in city)
{
<option data-region="@re.RegionID" value="@re.CityID">@re.CityName</option>
}
</select>
然后,我們需要遍歷 City 下拉列表的選項並相應地顯示/隱藏它們。 你的腳本應該是這樣的;
$(document).on("change", "#ddlregion", function() {
var selectedRegion = $(this).val();
$("#ddlcity").find("option").each(function() {
if ($(this).data("region") == selectedRegion) {
$(this).show();
} else {
$(this).hide();
}
});
});
見下面的靜態演示;
$(document).on("change", "#ddlregion", function() { var selectedRegion = $(this).val(); $("#ddlcity").find("option").each(function() { if ($(this).data("region") == selectedRegion) { $(this).show(); } else { $(this).hide(); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="ddlregion" name="RegionId"> <option value="0">Select Region</option> <option value="1">Region 1</option> <option value="2">Region 2</option> <option value="3">Region 3</option> </select> <select id="ddlcity" name="CityId"> <option data-region="0">Select City</option> <option data-region="1">City 1 in Region 1</option> <option data-region="1">City 2 in Region 1</option> <option data-region="2">City 1 in Region 2</option> <option data-region="3">City 1 in Region 1</option> <option data-region="3">City 2 in Region 2</option> <option data-region="3">City 3 in Region 3</option> <option data-region="3">City 4 in Region 4</option> </select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.