【发布时间】:2015-04-19 07:27:49
【问题描述】:
我正忙于 2 个下拉菜单。第一个是国家,加载正常,然后在国家改变时我调用 ajax 来填充省份下拉列表。
代码工作正常,当我在我的 ajax 调用中发出警报时,它会显示正在创建的正确数据,但它不会将其附加到下拉列表中,因此这些值不可用。
下拉
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Country:</label>
<div class="col-md-9 col-xs-7">
@Html.DropDownListFor(x => x.CountryId, (IEnumerable<SelectListItem>)ViewBag.CountryItems, "Please Select", new { @id = "ddlCountry", @class = "form-control select" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Province:</label>
<div class="col-md-9 col-xs-7">
@Html.DropDownListFor(x => x.ProvinceId, Enumerable.Empty<SelectListItem>(), "Please Select", new { @id = "ddlProvince", @class = "form-control select" })
</div>
</div>
阿贾克斯
<script>
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;
$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
$.each(data, function (i) {
var optionhtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionhtml);
});
}
});
});
</script>
背后的代码
public ActionResult GetProvinces(string countryId)
{
IEnumerable<SelectListItem> ProvinceItems = null;
if (!string.IsNullOrEmpty(countryId))
{
ProvinceItems = BusinessAPI.ProvinceManager.GetAllProvincesByCountryId(Convert.ToInt32(countryId)).Select(ci => new SelectListItem
{
Value = ci.Id.ToString(),
Text = ci.Name
});
}
return Json(ProvinceItems, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
您能用变量
optionhtml的console.log确认它的构造是否正确吗? -
您能否展示您向我们展示的部分视图的结果 html?
-
我得到一个这样填充的列表 -
标签: javascript c# ajax