I have two select in view filling through ViewData that are,
In view,
@{
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>
my script is like,
$("body").on("change", "#ddlregion", function () {
});
In script using IEnumerable<City> city
can i sort it according to region
Hopes for suggestions.
Edit:
my controller passing region and city from Ef like,
TribeEntities Db = new TribeEntities();
ViewData["regions"] = Db.Regions;
ViewData["cities"] = Db.Cities;
In your City dropdown, we need to add a data-attribute. I used data-region
. Use this as your City dropdown;
<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>
Then, we need to loop through the options of City dropdown and show/hide them accordingly. Your script should be like;
$(document).on("change", "#ddlregion", function() {
var selectedRegion = $(this).val();
$("#ddlcity").find("option").each(function() {
if ($(this).data("region") == selectedRegion) {
$(this).show();
} else {
$(this).hide();
}
});
});
See static demo below;
$(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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.