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

ASP.NET MVC下拉框值无法传递至Controller,参数为空报错求助

问题排查与解决

核心问题分析

报错的直接原因是:SpesGraduate方法的yr1参数为非可空int类型,但请求未传递该参数(或参数值为null),导致MVC模型绑定失败。触发场景可能是直接访问Action路径未带参数,或是表单提交逻辑冲突导致参数未正确传递。

分步解决方案

1. 修正控制器参数,兼容无参数场景

将控制器的yr1参数改为可空类型,或设置默认值,避免无参数时触发报错:

// 方案一:改为可空int,手动处理默认值
public ActionResult SpesGraduate(int? yr1)
{
    if (!yr1.HasValue)
    {
        yr1 = 2019; // 设置默认年份
    }
    int poid = GlobalHelper.UserPO(Session["UserPO"].ToString());
    int implYear = (int)Session["ImplementYear"];
    int selyr1 = yr1.Value;
    // 后续业务逻辑...
}

// 方案二:直接设置参数默认值(C# 4.0及以上支持)
public ActionResult SpesGraduate(int yr1 = 2019)
{
    int poid = GlobalHelper.UserPO(Session["UserPO"].ToString());
    int implYear = (int)Session["ImplementYear"];
    int selyr1 = yr1;
    // 后续业务逻辑...
}

2. 修复视图的表单提交逻辑

视图中location.reload()是多余的,会干扰表单提交(表单submit已会发起新请求加载页面),直接删除该行;同时给下拉框设置默认选中项,确保页面加载时就有有效参数:

<form action="/spesms/Reports/SpesGraduate" method="get" >
     <select name="yr1" id="yr1">
          <option value="2019" selected>2019</option> <!-- 添加selected设置默认选中 -->
          <option value="2020">2020</option>
          <option value="2021">2021</option>
          <option value="2022">2022</option>
      </select>
  </form>
<script>
        $(document).ready(function () {
            $('select').on('change', function () {
                $(this).closest('form').submit();
                // 删除 location.reload();
            });
        });
    </script>

3. 可选优化:用MVC内置方法生成表单路径

避免硬编码路径出错,建议使用Url.Action生成表单的action地址:

<form action="@Url.Action("SpesGraduate", "Reports")" method="get" >

内容的提问来源于stack exchange,提问作者Mark John Capistrano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:03:14