代码之家  ›  专栏  ›  技术社区  ›  Juan Salvador Portugal

带RadioButtonFor的Id

  •  0
  • Juan Salvador Portugal  · 技术社区  · 6 年前

    我正在尝试处理asp MVC 5中的单选按钮ID

    我是这样工作的

    class A
    {
       public bool? radio { get; set; }
    }
    

    在剃刀的视野里

    @Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { @id = "True"})
    @Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { @id = "False})
    

    它不会引起问题,但我在一个editortemplate中工作,我希望它已经生成 id @Html.IdFor(x => x.NeutroBT, true) @Html.IdFor(x => x.NeutroBT, false)

    有这种可能吗?我花了很多时间寻找,但没有找到类似的东西

    如果不可能,最好的办法是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   user3559349 user3559349    6 年前

    不需要使用 id 属性。相反,你可以使用 name 属性通过javascript选择或设置值(在任何情况下, @Html.IdFor() will only ever return , not the 身份证件 that you override in the

    另外,第二个参数 RadioButtonFor() 应该是 true false Model.NeutroBT !Model.NeutroBT ).

    要将标签与按钮关联,可以将其包装为 <label> ,例如

    <label>
        @Html.RadioButtonFor(x => x.NeutroBT, true, new { id = ""})
        <span>Yes</span>
    </label>
    <label>
        @Html.RadioButtonFor(x => x.NeutroBT, false, new { id = ""})
        <span>No</span>
    </label>
    

    请注意 new { id = "" } 身份证件 身份证件 属性。

    然后使用jQuery访问所选值

    var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();