【问题标题】:RadioButtonFor in ASP.NET MVC 2ASP.NET MVC 2 中的 RadioButtonFor
【发布时间】:2011-02-05 00:46:13
【问题描述】:

谁能提供一个如何正确使用 Html.RadioButtonFor 的简单示例?假设这是一个简单的场景,我的模型有一个名为 Gender 的字符串属性。我想显示两个单选按钮:“男性”和“女性”。

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 radiobuttonfor


    【解决方案1】:
    Male: <%= Html.RadioButtonFor(x => x.Gender, "Male") %>
    Female: <%= Html.RadioButtonFor(x => x.Gender, "Female") %>
    

    【讨论】:

    • 这很基本,但我认为正确的使用应该包括带有“for”属性的
    • 扩展@Larsenal 的评论,您可以这样做:&lt;%= Html.Label("Gender1", "Male:")%&gt;&lt;%= Html.RadioButtonFor(x =&gt; x.Gender, "Male", new {@id="Gender1"}) %&gt;
    • 赞成 @JustinP8 并反对答案 - 两个没有 @id= 的单选按钮为两个 html 元素提供相同的 id,这真的很讨厌!
    • 要添加到 JustinP8 的评论中,请注意像这样设置 id 不适用于嵌套模型。
    【解决方案2】:

    This question on StackOverflow 处理 RadioButtonListFor 并且答案也解决了您的问题(@Larsenal 它还包括带有“for”属性的标签)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多