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

如何将Html.DropDownList静态下拉框的选中值传递到Controller控制器方法

实现方案

有两种常用的实现方式,不需要修改现有下拉框的基础定义:

  • 方式1:直接从请求表单中获取选中值
    直接通过Request.Form根据下拉框的name属性取值即可,代码如下:
    public ActionResult Create(PatientInfo vdm_)
    {
        if (ModelState.IsValid)
        {
            PatientInfo vdm = new PatientInfo();
            // 直接按下拉框name属性取值,加空值兼容处理
            vdm.relationshipWithPatient = Request.Form["RelationshipWithFather"]?.ToString();
            // 后续业务逻辑
        }
    }
    
  • 方式2:利用MVC默认参数绑定自动获取
    给Action方法添加和下拉框name同名的参数,MVC会自动将选中值绑定到该参数上,代码如下:
    // 新增和下拉框name一致的字符串参数
    public ActionResult Create(PatientInfo vdm_, string RelationshipWithFather)
    {
        if (ModelState.IsValid)
        {
            PatientInfo vdm = new PatientInfo();
            vdm.relationshipWithPatient = RelationshipWithFather;
            // 后续业务逻辑
        }
    }
    

补充说明:如果后续没有其他逻辑依赖下拉框的name属性RelationshipWithFather,也可以直接将视图中下拉框的name修改为和模型属性一致的relationshipWithPatient,这样MVC会自动把选中值绑定到vdm_.relationshipWithPatient上,不需要手动赋值,直接把vdm_.relationshipWithPatient赋值给新对象即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:09:02