我有两个组合框。我以这种方式填充的第一个组合框,它工作正常:
@Html.DropDownListFor(
x => x.Town,
new SelectList(Model.Towns, "Value", "Text"),
"-- Select town --")
public IEnumerable<SelectListItem> Towns
{
get
{
List<DataRow> TownsListDB = OracleSelect("select * from Towns");
List<SelectListItem> townsItems = new List<SelectListItem>();
foreach (DataRow rw in TownsListDB)
{
townsItems.Add(new SelectListItem { Value = rw[0].ToString(),
Text = rw[1].ToString() });
}
return townsItems;
}
}
并且取决于城镇,我想显示医院列表:
@Html.DropDownListFor(
x => x.Hospital,
Enumerable.Empty<SelectListItem>(),
"-- Select hospital --")
我的 jQuery 代码是:
$('#Town').change(function() {
var selectedTown = $(this).val();
if (selectedTown != null && selectedTown != '') {
$.getJSON('@Url.Action("Hospitals")', { town: selectedTown },
function (hospitals) {
var hospitalsSelect = $('#Hospital');
hospitalsSelect.empty();
$.each(hospitals, function(i, hospital) {
hospitalsSelect.append($('<option/>', {
value: hospital.value,
text: hospital.text
}));
});
});
}
});
和 C#:
public ActionResult Hospitals(string town)
{
var modelHospital = new MedicalViewModel();
List<DataRow> HospitalsListDB = modelHospital.OracleSelect
("select * from Hospitals hh where hh.TownID = " + town);
List<SelectListItem> hospitalsItems = new List<SelectListItem>();
foreach (DataRow rw in HospitalsListDB)
{
//example:
//rw[0]=101111
//rw[1]=Dublin
hospitalsItems.Add(new SelectListItem { Value = rw[0].ToString(),
Text = rw[1].ToString() });
}
return Json(
hospitalsItems,
JsonRequestBehavior.AllowGet);
return Json(hospitalsItems, JsonRequestBehavior.AllowGet);
}
但它不起作用。如果我将此代码用作返回结果,则可以:
return Json(Enumerable.Range(1, 6).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
为什么组合框不适用于我的数据库列表结果?