MVC中未填充级联DropDownList

时间:2015-03-30 23:58:12

标签: c# jquery json asp.net-mvc

我想动态填充下拉列表。我有一个区{district_id,distrint_name}和Thana {thana_id,thana_name,district_id(fk)}的表。

控制器代码:

public class CenterController : Controller
{    
    string connection = ConfigurationManager.ConnectionStrings["CenterConnString"].ConnectionString;
    List<SelectListItem> districtList = new List<SelectListItem>();      
    List<SelectListItem> thanaList = new List<SelectListItem>();

    public ActionResult Index()
    {
        ViewBag.var1 = DistrictList();
        ViewBag.var2 = thanaList;        

        return View();
    }

    private SelectList DistrictList()  
    {
        using (SqlConnection conn = new SqlConnection(connection))
        {
            conn.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select distrint_name,district_id from tbl_district ", conn);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                districtList.Add(new SelectListItem { Text = myReader["distrint_name"].ToString(), Value = myReader["district_id"].ToString() });
            }
        }
        return new SelectList(districtList, "Value", "Text", "id"); //return the list objects in json form
    }

    public JsonResult ThanaList(int id)  
    {
        using (SqlConnection conn = new SqlConnection(connection))
        {
            conn.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select * from tbl_thana where district_id ='" + id + "' ", conn);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                thanaList.Add(new SelectListItem { Text = myReader["thana_name"].ToString(), Value = myReader["thana_id"].ToString() });
            }
        }
        return Json(thanaList, JsonRequestBehavior.AllowGet); //return the list objects in json form
    }
} 

查看代码:

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/modernizr-2.6.2.js"></script>

<script src="~/Scripts/jquery-2.1.3.min.js"></script>

<h2>Index</h2>

District          @Html.DropDownList("var1", "Choose District")
Thana             @Html.DropDownList("var2", "Choose Thana")
                                   @*dropdown with name var1, var2,var3 and with viewbag object*@
<script type="text/javascript">
    //initial var2, var3 are empty
    //dropdownlist name and viewbag object name must be same

    $(function () {
        $("#var1").change(function () {
            var name = $("#var1 :selected").val();  //if user select the tournament
            var url = 'Home/DistrictList';
            var data1 = { "id": name };
            $.post(url, data1, function (data) { //ajax call
                var items = [];
                items.push("<option value=" + 0 + ">" + "Choose Thana" + "</option>"); //first item
                for (var i = 0; i < data.length; i++) {
                    items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
                } //all data from the team table push into array
                $("#var2").html(items.join(' '));
            }); //array object bind to dropdown list
        });
});

</script>

<input type="submit" value="submit" />

问题是区域列表已填充好。但是第二个ddl没有绑定任何东西。通过调试可以看出代码没有通过&#34; Viewbag.var2 = thanalist&#34;。它没有调用Thanalist(int id)方法。 我无法摆脱错误。请帮忙。

1 个答案:

答案 0 :(得分:0)

我建议你首先阅读一些关于级联下拉菜单的文章(这是非常常见的事情)。您可能会在this answer中找到解决方案。如果您想通过一些良好实践查看更详细的版本,请查看this article

查看您的代码,我将负责为您提供一些建议:

  1. 将数据库代码移至单独的类。如果你继续将它保留在控制器动作方法中,它们将变得非常混乱。
  2. 使用Model而不是ViewBag。在您的特定示例中,使用ViewBag没有任何好处。
  3. 修改 要理解你想要达到的目标并不容易,但我想你想要默认选择一些District并填充Thana列表。

    以下是如何完成的示例。

    模型和演示数据访问层:

    public class District
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
    
    public class Thana
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
    
    public class Repository
    {
        public IEnumerable<District> GetDistricts()
        {
            // Dome data
            return new List<District>
            {
                new District {Id = 1, Text = "D1"},
                new District {Id = 2, Text = "D2"}
            };
        }
    
        public IEnumerable<Thana> GetThanas(int districtId)
        {
            // Demo data
            if (districtId == 1)
            {
                return new List<Thana> { new Thana {Id = 1, Text = "T11"}, new Thana {Id = 2, Text = "T12"}};
            }
    
            return new List<Thana> { new Thana {Id = 3, Text = "T21"}, new Thana {Id = 4, Text = "T22"} };
        }
    }
    

    控制器:

    public class IndexViewModel
    {
        public SelectList Districts { get; set; }
        public int DistrictId { get; set; }
    
        public SelectList Thanas { get; set; }
        public int ThanaId { get; set; }
    }
    
    public class HomeController : Controller
    {
        private readonly Repository _repository = new Repository();
    
        public ActionResult Index()
        {
            // Should be refactored to handle empty collections
            var districts = _repository.GetDistricts().ToList();
            var firstDistrict = districts.First();
            var thanas = _repository.GetThanas(firstDistrict.Id).ToList();
            var firstThana = thanas.First();
    
            var vm = new IndexViewModel
            {
                Districts = new SelectList(districts, "Id", "Text", firstDistrict),
                DistrictId = firstDistrict.Id,
                Thanas = new SelectList(thanas, "Id", "Text", firstThana),
                ThanaId = firstThana.Id
            };
    
            return View(vm);
        }
    
        public ActionResult GetThanas(int districtId)
        {
            return Json(_repository.GetThanas(districtId), JsonRequestBehavior.AllowGet);
        }
    }
    

    查看:

    @model IndexViewModel
    
    @Html.DropDownListFor(x => x.DistrictId, Model.Districts)
    @Html.DropDownListFor(x => x.ThanaId, Model.Thanas)
    
    @section scripts
    {
        <script>
            $(function () {
                $("#DistrictId").change(function () {
                    var self = $(this);
                    var items="";
                    $.getJSON("@Url.Action("GetThanas","Home")?districtId=" + self.val(),
                        function(data) {
                            $.each(data, function(index, item) {
                                items += "<option value='" + item.Id + "'>" + item.Text
                                    + "</option>";
                            });
                            $("#ThanaId").html(items);
                        });
                });
            });
    </script>
    }