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

如何将BeginForm中下拉列表选中值传递至Controller?已实现日期选择器传值

解决下拉列表选中值无法传递到Controller的问题

我懂你的困扰——datepicker的值能正常传到后端,但下拉选的DeviceId就是死活传不过去对吧?问题出在你当前用的是<a>标签来做下拉选项,这些标签不属于表单控件范畴,浏览器提交表单的时候根本不会把它们的值发给服务器。咱们稍微改改代码就能搞定:

修改后的View代码

@using (Html.BeginForm()) { 
    <div class="btn-group"> 
        <!-- 用来显示选中的DeviceId,默认提示用户选择 -->
        <button type="button" class="btn btn-info" id="selectedDeviceBtn">Select Device Id</button> 
        <button type="button" class="btn btn-info dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 
            <span class="sr-only">Toggle Dropdown</span> 
        </button> 
        <div class="dropdown-menu"> 
            @foreach (var item in Model.OrderBy(x=>x.DeviceId).Select(x => x.DeviceId).Distinct()) { 
                <!-- 给每个下拉项添加点击事件,把选中的ID赋值给隐藏输入框 -->
                <a class="dropdown-item" href="#" onclick="selectDevice(@item)">@item</a> 
            } 
        </div>
        <!-- 关键:添加隐藏输入框,name要和Controller的参数名完全一致 -->
        <input type="hidden" name="deviceid_dropdown" id="deviceid_dropdown" />
        <div class="col-md-1"> 
            <input type="submit" id="btnSubmit" name="Submit" class="btn btn-success" value="Submit" /> 
        </div> 
    </div> 
}

<!-- 简单的JS处理选中逻辑 -->
<script>
function selectDevice(deviceId) {
    // 把选中的DeviceId存入隐藏输入框
    document.getElementById('deviceid_dropdown').value = deviceId;
    // 更新按钮文字,让用户直观看到选中的内容
    document.getElementById('selectedDeviceBtn').textContent = deviceId;
}
</script>

为什么这样改?

  1. 隐藏输入框:添加了一个type="hidden"的input,它的name属性和你Controller方法里的参数名deviceid_dropdown完全匹配,提交表单时浏览器会自动把这个值发送到后端。
  2. 点击事件:给每个下拉项的<a>标签添加了点击函数,选中时把对应的DeviceId赋值给隐藏输入框,同时更新按钮文字提升用户体验。

Controller部分无需修改

你的现有Controller代码完全没问题,参数名已经和隐藏输入框的name对应上了:

public ActionResult Reports(DateTime? fromDate, DateTime? toDate, string deviceid_dropdown) { 
    // 现在可以正常拿到deviceid_dropdown的值了
}

这样修改后,当用户选中下拉项并点击提交按钮时,选中的DeviceId就会和datepicker的日期值一起传递到Controller的Reports方法里啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:39:10