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

如何获取Select/Option选中值并传入href实现教室信息更新功能

解决方案

方式1:通过JavaScript动态更新a标签链接(适用于需要保留a标签的场景)

asp-route-*属于服务端标签助手,仅在页面渲染阶段生效,页面加载完成后无法直接修改,因此需要通过前端监听下拉选择事件,动态更新a标签的href属性:

  1. 先给a标签添加id便于选择:
<select id="teachers">
    @foreach(var teacher in Model.Teachers){
        <!-- 建议选项展示教师名,value存Id,也可按你的需求保留展示Id -->
        <option value="@teacher.Id">@teacher.Name</option>
    }
</select>

<a id="updateLink" asp-controller="Classroom" asp-action="Update" asp-route-teacherId="">保存</a>
  1. 添加JS监听逻辑:
document.querySelector('#teachers').addEventListener('change', function() {
    const selectedId = this.value;
    const link = document.querySelector('#updateLink');
    // 如果你的路由是查询参数形式,比如 /Classroom/Update?teacherId=xxx
    const baseUrl = link.href.split('?')[0];
    link.href = `${baseUrl}?teacherId=${selectedId}`;
    
    // 如果你的路由是路径参数形式,比如 /Classroom/Update/123,改用下面的写法
    // const baseUrl = link.href.replace(/\/\d*$/, '');
    // link.href = `${baseUrl}/${selectedId}`;
})

方式2:改用表单提交(无需写JS,更简洁)

如果可以不用a标签,直接用get方式的表单提交,会自动把选中的教师ID拼接为请求参数:

<form asp-controller="Classroom" asp-action="Update" method="get">
    <select name="teacherId">
        @foreach(var teacher in Model.Teachers){
            <option value="@teacher.Id">@teacher.Name</option>
        }
    </select>
    <button type="submit">保存</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:24:03