javascript - 如何刷新与我在 mvc 中的第一个下拉列表相关的第二个下拉列表的新数据
问题描述
我有两个下拉列表。第一个是国家,第二个是省。两者的数据都是从数据库中加载的。我的 Country 表仅包含 2 个字段,CountryID 和 CountryName,Province 表有 3 个字段 CountryID、ProvinceID、ProvinceName。当我选择我的国家下拉列表时,我想刷新我的省下拉列表,这是我的代码:
<div class="form-group">
@Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@{
TBSWebApp.Database_Access_Layer.db dblayer2 = new TBSWebApp.Database_Access_Layer.db();
ViewBag.category = new SelectList(dblayer2.GetCountry(), "Country1", "Country");
}
@Html.DropDownListFor(model => model.Country ,
(IEnumerable<SelectListItem>)ViewBag.category,
new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
</div>
</div>
这个是用来调用我的数据库并填写记录的
public IEnumerable<TBSWebApp.Models.ContactAddress> GetCountry()
{
SqlCommand com = new SqlCommand("SELECT CountryID,CountryName FROM tblCountry ORDER BY Country", sqlconn);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
var tankReadings = new List<TBSWebApp.Models.ContactAddress>();
int x = 0;
foreach (DataRow drow in ds.Tables[0].Rows)
{
var tankReading = new TBSWebApp.Models.ContactAddress
{
Country1 = drow["CountryID"].ToString(),
Country = drow["CountryName"].ToString()
};
tankReadings.Add(tankReading);
}
return tankReadings.AsEnumerable();
}
public IEnumerable<TBSWebApp.Models.ContactAddress> GetProvince(string ID)
{
SqlCommand com = new SqlCommand("SELECT ProvinceID,ProvinceName FROM tblProvince WHERE CountryID ='" + ID + "' ORDER BY Province", sqlconn);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
var tankReadings = new List<TBSWebApp.Models.ContactAddress>();
int x = 0;
foreach (DataRow drow in ds.Tables[0].Rows)
{
var tankReading = new TBSWebApp.Models.ContactAddress
{
Province1 = drow["ProvinceID"].ToString(),
Province = drow["ProvinceName"].ToString()
};
tankReadings.Add(tankReading);
}
return tankReadings.AsEnumerable();
}
现在我不知道如何调用我的省下拉列表来填写基于所选国家的记录。
解决方案
您可以使用 javascript 捕获选择标记的事件更改并发送通过 ajax 选择的数据选项以获取新的提供者列表。
var selectDom = document.getElementById(\*id_your_select_tag*\);
selectDom.addEventListener("change", function() {
// call ajax at here
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// xhttp.responseText is response provider list.
// update select provider at here
}
}
xhttp.open("GET", "your_url_api_get_provider_list_by_id", true);
xhttp.send();
另一种方式,我可以使用部分视图来显示提供者列表。请参阅此处使用 Ajax 更新部分视图
推荐阅读
- julia - 使用 UInt128 数据类型时 Julia 中的大整数除法错误
- c++ - 仍然无法获得有关 IRIW 方案的真正根本原因解释
- apache-spark - Parquet 中的列索引
- django - 如何为表格可视化添加折线图并在 Django 项目中添加下拉菜单?
- mongodb - 如何在Mongoose MongoDb中获取一个部门的所有学生
- android - 在房间查询中获取可变参数大小
- flutter - 对 TabBar 使用 JSON 结果
- android - 状态栏突然改变大小
- java - 连接到 AxonServer 节点 [192.168.99.100:8124] 失败:内部:恐慌!这是一个错误
- css - 不同的订单项目和布局与 css3 通过分辨率与相同的 html