如何将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
相关产品推荐
相关产品推荐

