我正在尝试构建一个简单的国家/地区级联下拉列表。但我得到ajax调用失败来检索状态[对象对象]。我不知道问题出在哪里。我的国家名单来自一个工作正常的viewbag。但是状态列表不起作用甚至没有达到断点GetState()函数。请帮忙!以下是我的代码:
index.cshtml:
<div>
@Html.DropDownList("Country", (IEnumerable
<SelectListItem>)ViewBag.CountryList, "Select a country")
</div>
<div>
@Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "--Select State--", new { style = "width:200px" })
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetState")',
dataType: 'json',
data: { id: $("#Country").val() },
success: function (states) {
$.each(states, function (i,
state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve state.' + ex);
}
});
return false;
})
});
</script>
HomeController:
[HttpGet]
public JsonResult GetState(int? id)
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "--Select Country--", Value = "0" });
list.Add(new SelectListItem { Text = "AL", Value = "1" });
return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));
}