ASP.NET MVC 3级联组合框不起作用

时间:2013-05-03 11:02:16

标签: c# asp.net-mvc asp.net-mvc-3

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

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

为什么组合框不适用于我的DB结果?

2 个答案:

答案 0 :(得分:0)

使用此代码:

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

而不是在最后一行

return Json(hospitalsItems, JsonRequestBehavior.AllowGet);

答案 1 :(得分:0)

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