Ajax-Aufruf zum Auffüllen der Auswahlliste, wenn sich eine andere Auswahlliste ändert
Folgen auf vondieser Beitra, Ich versuche, eine Auswahlliste von 'Städten' zu füllen, wenn sich eine andere Auswahlliste von 'Ländern' ändert. Ich verfolgte den gleichen Ansatz wie der verknüpfte Beitrag und setzte Darins Vorschlag für den Erfolg um (). Es funktioniert die meiste Zeit großartig (was wirklich seltsam ist). Damit meine ich, dass von allen meinen "Ländern" 90% der Änderungsereignisse die Objekte der Auswahlliste (n) und die anderen 10% einen einzelnen Zeichenfolgewert zurückgeben. Warum sollte es variieren? Es sollte entweder funktionieren oder nicht ...
Aussich
<!--Country-->
<div class="form-group col-md-3">
<label class="control-label ">City </label>
<br />
<select id="Country" name="Country" class="form-control">
<option value="">List of countries from Model...</option>
</select>
</div>
<!--City-->
<div class="form-group col-md-3">
<label class="control-label ">City </label>
<br />
<select id="City" name="City" class="form-control">
<option value="">Select a country first...</option>
</select>
</div>
<!--Inside my script -->
<script>
$('#Country').change(function () {
var selectedValue = $(this).val();
$.ajax({
url: '@Url.Action("CityDropDownList", "Home")',
type: "GET",
data: { country: selectedValue },
success: function (result) {
var cityDropDownList = $('#City');
cityDropDownList.empty();
$.each(result, function () {
cityDropDownList.append(
$('<option/>', {
value: this.Value,
text: this.Text
})
);
});
}
});
});
</script>
Regle
public JsonResult CityDropDownList(string country)
{
var results = (from c in db.PageStats
where c.Country.Equals(country)
orderby c.City
select c.City).ToList().Distinct();
//db.PageStats.Where(x => x.Country.Equals(country)).OrderBy(x => x.City).Select(x => x.City).Distinct().ToList();
List<SelectListItem> cities = new List<SelectListItem>();
foreach(var item in results)
{
SelectListItem city = new SelectListItem
{
Text = item,
Value = item
};
cities.Add(city);
}
return Json(cityList, JsonRequestBehavior.AllowGet);
}