Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC C# 动态单选按钮获取表单集合

2024年02月23日33dflying

我有一个表单,其中可以在 View 中动态生成多个单选按钮,在提交的表单上我如何收集 Controller 中的值。例如,有动态生成的单选按钮,如性别(男性和女性)、教育(BS、MS、BCS)。我怎样才能在容器中获得值(value)。

请您参考如下方法:

如果您知道单选按钮的名称,则可以使用操作参数。如果名称是任意的,您可以从 FormCollection 中获取值传递给您的 POST 操作的参数(它是一个 NameValueCollection,因此您可以遍历键并获取相应的值)。

我个人建议您使用确定性名称:

Gender: 
<input type="radio" value="M" name="radios[0]" /> 
<input type="radio" value="F" name="radios[0]" /> 
 
Education: 
<input type="radio" value="BS" name="radios[1]" /> 
<input type="radio" value="MS" name="radios[1]" /> 
<input type="radio" value="BCS" name="radios[1]" /> 

在你的 Controller Action 中你可以使用一个集合:

[HttpPost] 
public ActionResult Update(string[] radios) 
{ 
    // The radios collection will contain the selected values like: 
    // radios[0] = "F" 
    // radios[1] = "MS" 
    ... 
}