ASP.Net Core MVC中实现单选按钮切换文本框与下拉列表
实现单选按钮切换文本框与下拉列表
步骤1:调整HTML结构
同时保留文本框和下拉列表,给下拉列表添加初始隐藏样式,确保页面加载时只显示文本框:
<style> .table1 { display: inline-block } .l3n-select { display: none; } </style> <div class="table1"> <label> Level 3 Num</label> <!-- 文本框 --> <input type="text" name="Level3Num" class="l3n-input" placeholder="Level 3 Num" maxlength="100" style="margin:5px;width:400px; height:30px;border:1px solid #01579B;" /> <!-- 下拉列表(初始隐藏) --> <select name="Level3Num" class="l3n-select" style="margin:5px;width:400px; height:30px;border:1px solid #01579B;"> <option value="">请选择已有Level 3 Num</option> <option value="L3-001">L3-001</option> <option value="L3-002">L3-002</option> <option value="L3-003">L3-003</option> </select> <label> <input type="radio" name="editList" value="new" checked />New </label> <label> <input type="radio" name="editList" value="existing" />Existing </label> </div>
注:给New单选按钮加上checked属性,确保页面默认选中“New”,对应显示文本框;两个输入控件设置相同的name,方便后端统一接收值。
步骤2:添加切换逻辑(原生JavaScript)
在页面末尾添加JS代码,监听单选按钮的切换事件,控制文本框和下拉列表的显示/隐藏:
// 获取目标元素 const radioButtons = document.querySelectorAll('input[name="editList"]'); const textInput = document.querySelector('.l3n-input'); const selectInput = document.querySelector('.l3n-select'); // 绑定切换事件 radioButtons.forEach(radio => { radio.addEventListener('change', function() { if (this.value === 'new') { textInput.style.display = 'inline-block'; selectInput.style.display = 'none'; } else if (this.value === 'existing') { textInput.style.display = 'none'; selectInput.style.display = 'inline-block'; } }); });
ASP.NET Core MVC后端接收提示
后端模型可以直接定义对应字段,比如:
public class LevelModel { public string Level3Num { get; set; } public string EditList { get; set; } // 接收单选按钮选中的值:new/existing }
控制器方法接收模型时,会自动获取当前显示控件的Level3Num值。
内容的提问来源于stack exchange,提问作者Sofiya kalan
相关产品推荐
相关产品推荐

