ASP.NET MVC 2中的RadioButtonFor

Lar*_*nal 15 asp.net-mvc radiobuttonfor asp.net-mvc-2

有人可以提供一个如何正确使用Html.RadioButtonFor的简单示例吗?让我们说这是一个简单的场景,我的模型有一个名为Gender的字符串属性.我想显示两个单选按钮:"男性"和"女性".

在编辑视图中保留所选值的同时实现此最简洁的方法是什么?

Dar*_*rov 26

Male: <%= Html.RadioButtonFor(x => x.Gender, "Male") %>
Female: <%= Html.RadioButtonFor(x => x.Gender, "Female") %>
Run Code Online (Sandbox Code Playgroud)

  • 扩展@Larsenal的评论,你可以这样做:`<%= Html.Label("Gender1","Male:")%> <%= Html.RadioButtonFor(x => x.Gender,"Male", new {@ id ="Gender1"})%>` (12认同)
  • 这是非常基本的,但我认为正确使用将包括<label>标签,其中"for"属性将其与单选按钮相匹配. (3认同)

Mac*_*Mac 5

StackOverflow上的这个问题处理RadioButtonListFor,答案也解决了你的问题(@Larsenal它还包含带有"for"属性的标签)