【问题标题】:MVC3 RadioButtonFor - how to set checked="checked" properlyMVC3 RadioButtonFor - 如何正确设置checked="checked"
【发布时间】:2011-12-04 22:46:19
【问题描述】:

我正在尝试使用 MVC3 + Razor 实现类似于以下内容的 html:

<input id="x1" type="radio" value="true" name="UseExistingNumberX" checked="checked"/>
<input id="x2" type="radio" value="false" name="UseExistingNumberX"  />

由于某种原因,我无法让它工作。当我尝试以下操作时:

@Html.RadioButtonFor(Function(m) m.UseExistingNumber, "true", New With {.id = "r1", .checked = "checked"}) Use Existing Service
@Html.RadioButtonFor(Function(m) m.UseExistingNumber, "false", New With {.id = "r2"}) Add New Service

我得到这个 html 输出:

<input type="radio" value="true" name="UseExistingNumber" id="r1" data-val-required="The UseExistingNumber field is required." data-val="true" checked="checked"> Use Existing Service
<input type="radio" value="false" name="UseExistingNumber" id="r2" checked="checked"> Add New Service

这是我的模特:

Public Class SelectiveServiceStep1Model


    <Required(ErrorMessage:="Postcode is required.")> _
    <RegularExpression("^\d*[0-9]$", ErrorMessage:="Your Postcode must contain only digits.")> _
    Public Property Postcode As String

    Public Property UseExistingNumber As Boolean

End Class

如果您发现生成的 html 存在 2 个问题:

  1. 我只在 Razor 中将checked="checked" 设置为"r1",但由于某种原因,它还将checked="checked" 设置为"r2"。为什么?
  2. 我没有在我的模型中将“UseExistingNumber”标记为“必填”字段,但为什么“r1”呈现为“da​​ta-val-required”属性?

注意:我知道我可以直接将html写入Razor,我也知道我可以编写自己的扩展来渲染我想要的html。我简直不敢相信我已经不能使用内置的了,我肯定错过了什么吧?

谢谢

【问题讨论】:

    标签: html asp.net-mvc vb.net razor radio-button


    【解决方案1】:
    1. 你得到checked属性是因为model的值为true。
    2. 正在应用 required 标志,因为 non-billable bool 暗示它是强制性的。

    当我过去这样做时,我使用了 HTML.RadioButton 而不是 RadioButtonFor。请注意,“字段”是您的字段。我通常会将它放在编辑器模板中。

    • @Html.RadioButton("field", "True", new { id = (ViewData.TemplateInfo.GetFullHtmlFieldId("field") + "Yes")}) 是的
    • @Html.RadioButton("field", "False", new { id = (ViewData.TemplateInfo.GetFullHtmlFieldId("field") + "No")}) 不
    @Html.ValidationMessage("")

     

    【讨论】:

    • 1.我的模型是空的,所以默认值为“False” - 而不是“True”。 2. 在我更改为布尔值之后?它运作良好,即不再需要“data-val-required”属性。但是,是的,仍然不确定第 1 个问题
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 2011-02-05
    • 2011-05-27
    • 2017-07-17
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多