2

我有两个组合框。我以这种方式填充的第一个组合框,它工作正常:

@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
                );

为什么组合框不适用于我的数据库列表结果?

4

2 回答 2

0

我发现了问题所在。听起来很有趣,我的 jQuery 代码中只需要大写字母:code select.append($('', { value:hospital. Value , text: hospital. Text }

于 2013-05-04T07:48:18.030 回答
0

使用此代码:

return Json(hospitalsItems.ToList(), JsonRequestBehavior.AllowGet);

而不是在最后一行

return Json(hospitalsItems, JsonRequestBehavior.AllowGet);
于 2013-05-03T11:13:55.523 回答