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

如何在Option标签中使用ActionLink向控制器传递参数

问题根因

你的代码有5个核心错误,导致功能完全不符合预期:

  • Html.ActionLink 方法返回的是完整的<a>超链接HTML标签,不是纯URL字符串,把返回值塞到data-url属性里,属性值会被混入大量HTML标签代码,完全无法作为跳转地址使用。
  • 表单提交逻辑完全不匹配需求:你给select绑定的onchange="this.form.submit()"只会触发表单原生提交,提交时只会拼接表单内带name属性的控件参数,也就是只会传sectionId这一个参数,根本不会读取option上的data-url属性值,也不会携带你需要的subSectionID、subsectionName两个参数。
  • option标签内部没有填充显示文本,<option></option>中间为空,下拉列表渲染后看不到任何选项文字。
  • 表单action属性值末尾多了一个多余空格:action="Update ",可能导致路由匹配失败。
  • Html.ActionLink指定的目标Action是UpdateBoard,和你预期要访问的Update接口地址不一致。
可直接运行的修正方案

提供两种常用实现,按需选择即可:

方案1:原生GET表单提交(最简洁,无多余逻辑)

直接调整表单控件的参数名和接口要求匹配,不需要自定义属性:

@* 注意action去掉末尾空格 *@
<form action="Update" method="get" class="select-menu">
<select id="sectionId"
        name="subSectionID"
        class="selectpicker"
        title="Section"
        data-width="100%"
        data-live-search="true">

       @foreach (var item in Model)
       {
           @* option标签内填充显示文本 *@
           <option value="@item.Value">@item.Text</option>
       }
  </select>
  @* 隐藏域存储要传递的subsectionName参数 *@
  <input type="hidden" name="subsectionName" id="subsectionName" />
</form>

<script>
const sectionSelect = document.getElementById('sectionId');
const nameInput = document.getElementById('subsectionName');
// 选中选项时同步给隐藏域赋值,提交时自动携带参数
sectionSelect.addEventListener('change', function(){
    const selectedOpt = this.options[this.selectedIndex];
    nameInput.value = selectedOpt.text;
    this.form.submit();
})
</script>

选中选项提交后,自动生成的请求地址完全符合你的预期:http://localhost:60082/Update?subSectionID=27&subsectionName=Something

方案2:直接读取预生成URL跳转(适合固定路由规则场景)

如果不需要保留表单结构,可以直接用Url.Action生成纯URL地址存在option上,选中时直接跳转,不需要表单提交逻辑:

<select id="sectionId"
        class="selectpicker"
        title="Section"
        data-width="100%"
        data-live-search="true"
        onchange="window.location.href = this.options[this.selectedIndex].dataset.url">

       @foreach (var item in Model)
       {
           @* 用Url.Action生成纯URL,不要用Html.ActionLink *@
           <option value="@item.Value" 
                   data-url="@Url.Action("Update", new { subSectionID = item.Value, subsectionName = item.Text })">
                   @item.Text
           </option>
       }
</select>

提示:如果参数包含中文、特殊字符,Razor会自动做URL编码,不需要额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:39:33