You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 5中如何通过select的onchange事件高效触发Action实现联动下拉

最优实现方案:AJAX局部异步加载二级下拉选项

你原来的整页跳转方案确实存在冗余问题,用AJAX异步拉取对应区域的操作项,只更新第二个下拉框的内容即可,不需要整页重载,实现逻辑如下:


步骤1:后端新增接口返回对应区域的操作列表

在你的控制器中新增一个Action专门处理操作项查询,返回JSON格式数据:

[HttpGet]
public JsonResult GetOperationsByArea(string areaClave)
{
    List<YourOperationModel> operationList = new List<YourOperationModel>();
    SqlConnection con = (SqlConnection)_contextFRTFGRAL.Database.GetDbConnection();
    SqlCommand cmd = con.CreateCommand();
    
    con.Open();
    // 拼接查询条件,选ALL的时候返回所有激活的操作
    string query = "SELECT operationId, operationName FROM cert.operationCerts WHERE Activa = 1 ";
    if(areaClave != "NA")
    {
        query += " AND areaClave = @AreaClave ";
        cmd.Parameters.AddWithValue("@AreaClave", areaClave);
    }
    query += " ORDER BY operationName ASC ";
    cmd.CommandText = query;
    
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            operationList.Add(new YourOperationModel
            {
                OperationId = reader["operationId"].ToString(),
                OperationName = reader["operationName"].ToString()
            });
        }
    }
    con.Close();
    return Json(operationList, JsonRequestBehavior.AllowGet);
}

注意把代码中的YourOperationModel替换成你自己的操作项实体类,字段名、表名也对应你自己的业务库结构修改,这里用参数化查询是为了避免SQL注入风险。


步骤2:视图中新增二级下拉框

在原来的区域下拉框下方添加第二个下拉框:

<select id="OperationSelect" class="custom-select" name="OperationId">
    <option value="" selected>请先选择区域</option>
</select>

步骤3:修改前端JS逻辑,用AJAX异步拉取数据

替换你原来的AreasSelect方法:

function AreasSelect() {
    const selectedArea = document.getElementById("AreaSelect").value;
    const opSelect = document.getElementById("OperationSelect");
    // 先清空原有选项,提示加载中
    opSelect.innerHTML = '<option value="" selected>加载中...</option>';
    
    // 发起异步请求拿对应区域的操作项
    fetch(`/你的控制器名称/GetOperationsByArea?areaClave=${selectedArea}`)
        .then(res => res.json())
        .then(data => {
            opSelect.innerHTML = '';
            // 遍历返回结果添加选项
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item.operationId;
                option.textContent = item.operationName;
                opSelect.appendChild(option);
            });
        })
        .catch(err => {
            opSelect.innerHTML = '<option value="" selected>加载失败,请重试</option>';
            console.error('请求操作列表失败:', err);
        });
}

如果你项目引入了jQuery,也可以换成$.ajax写法,核心逻辑完全一致。


方案优势

  • 无需整页刷新,用户体验更流畅
  • 降低服务器压力,不需要重新渲染整个页面、不需要重复加载页面其他静态资源
  • 不会丢失页面原有表单内容:整页刷新如果用户已经填了其他表单项会被清空,该方案不存在这个问题

内容的提问来源于stack exchange,提问作者Miguel V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:39:03