【问题标题】:Change Id of MVC Radiobuttonfor or trigger jQuery function更改 MVC Radiobuttonfor 的 Id 或触发 jQuery 函数
【发布时间】:2014-08-07 22:11:35
【问题描述】:

在 MVC Radiobuttonfor helper 中使用以下表示法,我可以创建一个单选,如果模型中存在值,则该单选将选择默认按钮。

@Html.RadioButtonFor(x => x.Username, "Y", Model.Username == "Y" ? new { Checked = "checked", id = "YUserName" } : null) No: 
@Html.RadioButtonFor(x => x.Username, "N", Model.Username == "N" ? new { Checked = "checked" } : null)

但是id = "YUserName" 不适用于值为“Y”的单选按钮

如果我在radiobuttonfor helper 中没有评估表达式,我可以用值“Y”更改收音机的id,即:

@Html.RadioButtonFor(x => x.UsePriorFinancialInfo, "Y", new { id = "YUsePriorFinancialInfo" }) 
@Html.RadioButtonFor(x => x.UsePriorFinancialInfo, "N")

有没有办法使用评估表达式将自定义 ID 应用于其中一个单选按钮?如果没有,如果选择了任一单选按钮,是否有办法触发 jQuery 函数? - 谢谢

【问题讨论】:

    标签: jquery asp.net-mvc html-helper radiobuttonfor


    【解决方案1】:

    首先,删除Checked = "checked"RadioButtonFor 助手将分配checked 的值。这对我来说很好用

    @Html.RadioButtonFor(x => x.Username, "Y", Model.Username == "Y" ? new { id = "YUserName" } : null) Yes:
    @Html.RadioButtonFor(x => x.Username, "N") No:
    

    并呈现以下html

    <input checked="checked" id="YUserName" name="Username" type="radio" value="Y">
    <span>Yes</span>
    <input id="Username" name="Username" type="radio" value="N">
    <span>No</span>
    

    您确定属性Username 的值设置为“Y”吗?

    【讨论】:

    • Stephen - 您是正确的,如果选中该输入,将设置自定义 ID (YUserName)。无论是否检查输入,我都想更改 id。我知道只有在检查时才设置 id,因为 html 属性是在问号之后指定的,但是我找不到在问号之前指定属性的方法。
    • 抱歉,我不确定你想达到什么目的。
    • 我需要为集合中的每个单选按钮设置唯一的 ID,以便仅将 jQuery 函数附加到单选按钮的一个实例。然而,正如本文 [链接]goodcoffeegoodcode.blogspot.com/2010/02/… 中所述,MVC 单选按钮用于帮助程序将相同的 Id 应用于单选按钮集合的所有按钮。正如链接的文章所暗示的那样,我可以通过应用 new {@id = ""} 来覆盖此行为,但这会阻止我为单选按钮集合分配默认选择。
    • jquery 函数是否应用于选中的单选按钮?如果是这样,您可以使用:checked 选择器,或者如果您知道顺序,您可以使用.eq()。在任何情况下,您都应该删除new { Checked = "checked" .. 位,并让助手根据UserName 的值为您设置它
    • 感谢您的帮助。我通过应用一个类并将我的 jQuery 函数附加到该类来解决这个问题。此问题已解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2012-11-22
    • 2019-08-21
    • 2011-08-26
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多