如何解决如何使用 ASP.Net MVC 级联 DropDownList
我已经使用 ASP.Net MVC 实现了 Cascading (Dependent) 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>
解决方法
我会使用 ajax 来做这样的事情:
<script>
$(document).ready(function () {
$("#country").change(function () {
BindStatesForDropDown();
});
});
function BindStatesForDropDown() {
var objParam = new Object();
objParam.Id = $("#country").val();
$.ajax({
type: "POST",url: "/pageControl/getstate",contentType: "application/json",data: JSON.stringify(objParam),success: function (res) {
$("#state").empty();
if (res.length > 0) {
$.each(res,function (key,data) {
$("#state").append($("<option></option>").val(data.id).html(data.name));
});
}
},error: function (res) {
}
});
}
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。