我想動態填充下拉列表。我有一張地區分區{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幫助。
根據你的代碼,爲什麼你認爲'Viewbag.var2 = thanalist'應該調用'Thanalist(int id)'? – 2015-03-31 03:51:43
我正在描述這裏發生了什麼..Plz找到了bug.2nd ddl沒有填充。代碼有什麼問題? – 2015-03-31 07:11:00