【发布时间】:2021-07-04 10:15:02
【问题描述】:
我已经使用 ASP.Net MVC 实现了级联(依赖)DropDownList。但是重定向到 index.cshtml 不起作用,因为表单上的所有 DropDownList 都是空的,除了正确填充的第一个 DropDownList 。如何根据国家下拉列表的数据填充州下拉列表?
控制器
public ActionResult page()
{
string con = Properties.Settings.Default.db;
MySqlConnection con_main = new MySqlConnection(con);
con_main.Open();
MySqlCommand listK = new MySqlCommand("", con_main);
var listcountry = new List<dropdownc>();
listc.CommandText = "SELECT id, name FROM master_country";
MySqlDataReader rc = listc.ExecuteReader();
while (rc.Read())
{
listcountry.Add(new dropdownc
{
id = rc[0].ToString(),
name = rc[1].ToString()
});
}
ViewBag.country = new SelectList(listcountry, "id", "name");
con_main.Close();
return View();
}
[HttpPost]
public JsonResult getstate(string Id)
{
string con = Properties.Settings.Default.db;
MySqlConnection con_main = new MySqlConnection(con);
MySqlCommand lists = new MySqlCommand("", con_main);
var liststate = new List<dropdowns>();
con_main.Open();
listsc.CommandText = "SELECT id, name FROM master_state WHERE id_country = '" + Id + "' ";
MySqlDataReader rs = listsc.ExecuteReader();
while (rs.Read())
{
liststate.Add(new dropdowns
{
id = rs[0].ToString(),
name = rs[1].ToString()
});
}
con_main.Close();
return Json(liststate, JsonRequestBehavior.AllowGet);
}
查看
<div id="dropDownListdiv">
@using (Html.BeginForm("Index", "CascadingDropDownList", FormMethod.Post))
{
@Html.DropDownList("country", "Select Country")
@Html.DropDownList("state", new SelectList(" "), "Select State")
<input type="submit" value="Submit" />
}
</div>
视图上的 JavaScript 代码
<script>
$(document).ready(function () {
$("#country").change(function () {
$.get("~/pageControl/getstate", { Id: $("#country").val() }, function (data) {
$("#state").empty();
$.each(data, function (index, row) {
$("#state").append("<option value='" + row.id + "'>" + row.name + "</option>")
});
});
})
});
</script>
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-mvc-4