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

ASP.NET MVC中点击按钮传递DropdownList值至Edit控制器的方法问询

嘿,我来帮你搞定这个问题!你现在的核心困扰是静态的<a>标签没法实时获取下拉框的选中值,对吧?这里有几种靠谱的实现思路,你可以根据需求选:

方法一:用JavaScript动态更新链接的href

因为页面加载后<a>标签的href是固定的,所以我们可以监听下拉框的change事件,实时修改链接里的SelectedAPt参数值。

保留你原有的下拉框和按钮代码,然后添加这段JS:

// 获取下拉框和GO按钮元素
const aptDropdown = document.getElementById('SelectedAPt');
const goButton = document.querySelector('a[href*="Edit"]');

// 监听下拉框选中变化
aptDropdown.addEventListener('change', function() {
  const selectedValue = this.value;
  // 替换href里的SelectedAPt参数值
  const updatedHref = goButton.href.replace(/SelectedAPt=\?\?\?/, `SelectedAPt=${encodeURIComponent(selectedValue)}`);
  goButton.href = updatedHref;
});

// 页面加载时初始化一次(如果下拉框有默认选中值的话)
window.addEventListener('load', function() {
  if (aptDropdown.value) {
    const updatedHref = goButton.href.replace(/SelectedAPt=\?\?\?/, `SelectedAPt=${encodeURIComponent(aptDropdown.value)}`);
    goButton.href = updatedHref;
  }
});

这样每次切换下拉选项时,按钮的链接都会自动更新成选中的值,点击就能正确传递参数了。

方法二:改用表单提交(更符合MVC常规玩法)

这种方法不需要写JS,直接用MVC的表单机制来传递参数,更简洁可靠:

@using (Html.BeginForm("Edit", "APtTitle", FormMethod.Get))
{
    <!-- 隐藏字段传递aPtId -->
    @Html.HiddenFor(m => m.APtTitleData.aPtId)
    
    <!-- 你的下拉框 -->
    @Html.DropDownListFor(m => m.APtTitleData.apt, (IEnumerable<SelectListItem>)ViewBag.apt, "-Select Apt-", new { id = "SelectedAPt", name= "SelectedAPt" })
    
    <!-- 把a标签换成提交按钮,也可以加样式改成链接样子 -->
    <button type="submit" style="background:none; border:none; color:blue; text-decoration:underline; cursor:pointer;">GO</button>
}

表单用GET方法提交时,会自动把表单里的字段(包括下拉框的选中值和隐藏的aPtId)拼到URL里,和你原来的<a>标签行为完全一致,而且MVC会自动帮你绑定到控制器的参数上。

方法三:保留a标签样式+表单提交(折中方案)

如果你特别想保留<a>标签的样式,也可以用JS触发隐藏表单的提交:

<!-- 隐藏的表单 -->
@using (Html.BeginForm("Edit", "APtTitle", FormMethod.Get, new { id = "editForm" }))
{
    @Html.HiddenFor(m => m.APtTitleData.aPtId)
    @Html.Hidden("SelectedAPt", "", new { id = "hiddenAptValue" })
}

<!-- 你的下拉框和原a标签 -->
@Html.DropDownListFor(m => m.APtTitleData.apt, (IEnumerable<SelectListItem>)ViewBag.apt, "-Select Apt-", new { id = "SelectedAPt", name= "SelectedAPt" })
<a href="javascript:void(0)" id="goButton">GO</a>

<script>
const aptDropdown = document.getElementById('SelectedAPt');
const goButton = document.getElementById('goButton');
const hiddenAptValue = document.getElementById('hiddenAptValue');
const editForm = document.getElementById('editForm');

goButton.addEventListener('click', function() {
    // 把下拉选中值赋值给隐藏字段
    hiddenAptValue.value = aptDropdown.value;
    // 提交表单
    editForm.submit();
});
</script>

小建议

个人更推荐方法二,因为它不需要额外的JS代码,完全利用MVC的原生机制,不容易出bug,维护起来也更简单。如果必须用<a>标签,方法一的动态更新链接也很稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:14:12