前台
<select id="Warehouse" name="Warehouse" onchange="firstSel();">
<option value="0">请选择</option>
</select>
<select id="tagImageId" name="Reservoir">
</select>
<script>
$.ajax({
url: '@Url.Action("AAAA")',//同文件夹下的json文件路径
type: "GET",//请求方式为get
dataType: "json", //返回数据格式为json
success: function (data) {//请求成功完成后要执行的方法
console.log(data);
//获取jsonTip的div
var $jsontip = $("#Warehouse");
//存储数据的变量
var strHtml = "";
//清空内容
$jsontip.empty();
//将获取到的json格式数据遍历到div中
$.each(data, function (infoIndex, info) {
strHtml += "<option value='" + info['warehouseName'] + "'>" + info['warehouseName'] + "</option>"
})
//显示处理后的数据
$jsontip.html(strHtml);
}
})
</script>
<script>
function firstSel() {
$("#tagImageId").empty();
var applicationId = $('#Warehouse option:selected').val();
$.ajax({
url: '@Url.Action("B")',
data: { "applicationId": applicationId },
dataType: "json",
type: "POST",
traditional: true,
success: function (data) {
console.log(data);
//获取jsonTip的div
var $jsontip = $("#tagImageId");
//存储数据的变量
var strHtml = "";
//清空内容
$jsontip.empty();
//将获取到的json格式数据遍历到div中
$.each(data, function (infoIndex, info) {
if (data != null) {
strHtml += "<option value='" + info['warehouseName'] + "'>" + info['warehouseName'] + "</option>"
}
else {
strHtml += "<option value='" + "-1" + "'>" + "-暂无关联的应用-" + "</option>"
}
})
//显示处理后的数据
$jsontip.html(strHtml);
}
});
}
</script>
后台
public class BBB
{
public string WarehouseName { get; set; }
}
[HttpPost]
public ActionResult B(string applicationId)
{
var ReservoirList = dataContext.DataReservoirs.ToList();///换成自己需要读的数据库
ReservoirList = ReservoirList.Where(t => t.Warehouse.Contains(applicationId)).ToList();///查询符合选中的数据
List<BBB> ReservoirInputs = new List<BBB>();
if (ReservoirList != null)
{
foreach (var item in ReservoirList)
{
///遍历符合条件的数据至JSON
BBB ReservoirInput = new BBB
{
WarehouseName = item.WarehouseName,
};
ReservoirInputs.Add(ReservoirInput);
}
}
return Json(ReservoirInputs);
}
[HttpGet]
public ActionResult AAAA()
{
var storehouseList = dataContext.DataStorehouses.ToList();///换成自己需要读的数据库
List<StorehouseInput> StorehouseInputs = new List<StorehouseInput>();///查询符合选中的数据
foreach (var item in storehouseList)
{
StorehouseInput storehouseInput = new StorehouseInput()
{
///遍历符合条件的数据至JSON
WarehouseName = item.WarehouseName,
};
StorehouseInputs.Add(storehouseInput);
}
return Json(StorehouseInputs);
}
该代码段展示了如何使用Ajax和jQuery在前端实现两个下拉列表的联动。当用户在第一个下拉列表(Warehouse)选择一项时,会触发AjaxGET请求获取相关数据填充第二个下拉列表(tagImageId)。后端使用C#处理请求,根据传入的applicationId查询数据库并返回JSON数据。
4527

被折叠的 条评论
为什么被折叠?



