2015-03-30 114 views
1

我想動態填充下拉列表。我有一張地區分區{district_id,distrint_name}和Thana {thana_id,thana_name,district_id(fk)}。級聯DropDownList未在MVC中填充

控制器代碼:

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" /> 

的問題是,區列表中填充ok.But第二DDL不綁定任何東西。通過調試可以看出代碼不會通過「Viewbag.var2 = thanalist」運行。它不會調用Thanalist(int id)方法。 我不能擺脫error.please幫助。

+0

根據你的代碼,爲什麼你認爲'Viewbag.var2 = thanalist'應該調用'Thanalist(int id)'? – 2015-03-31 03:51:43

+0

我正在描述這裏發生了什麼..Plz找到了bug.2nd ddl沒有填充。代碼有什麼問題? – 2015-03-31 07:11:00

回答

0

我建議你首先閱讀一些關於級聯下拉的文章(這是很常見的事情)。您可能會在this answer中找到解決方案。如果您想查看更詳細的版本以及一些良好做法,請檢查this article

看你的代碼,我會承擔責任,給你幾個建議:

  1. 移動數據庫的代碼單獨的類。如果你繼續保持控制器的行動方式,他們將變得非常混亂。使用Model而不是ViewBag。在您的具體示例中,使用ViewBag沒有任何好處。

編輯: 這不是很容易理解你想要達到的目標,但我猜你想要一些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> 
} 
+0

這些不是我對這個問題的回答。我知道使用視圖模型的慣例。這是一個巨大項目的故事,此後將修改和合並此代碼。現在嘗試解決這個錯誤。 thnx提前。我已經通過這些鏈接之前,你建議他們。@ Aleksandr – 2015-03-31 10:53:31

+0

我編輯了答案。希望能幫助到你。 – 2015-03-31 12:07:26