1
this postの後に、別の選択リストの「国」が変更されたときに、「都市」の選択リストを設定しようとしています。私はリンクされたポストと同じアプローチに従いました。そしてダーリンの成功のための提案を実装しました。それは時間の偉大な 'ほとんど'(これは本当に奇妙です)動作します。つまり、私の「国」の中で、変更イベントの90%が選択リスト項目オブジェクトを返し、残りの10%が単一の文字列値を返します。それはなぜ変わるのですか?それはすべきいずれかの仕事やない...別の選択リストが変更されたときにAjaxコールを選択リストに追加
ビュー
<!--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>
コントローラ
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);
}
を解決しましたか?あなたは配列の代わりに単一の文字列を返すと言っていますか? – Shyju
90%の成功の場合、1または複数の[object Object]のいずれかを返します。 10%の場合は、すべての都市を巨大な文字列で表示します。私は警告(結果)を追加しました。成功の直後(){デバッグする。 – JReam
それは奇妙に聞こえる!あなたのコードは正常に見えます。変更イベント登録をdocument.readyイベントの中に置くことをお勧めします。 – Shyju